Yes, that can definitely happen — let me explain why ๐
๐ง What em really means
-
1em= the font size of the element (or its parent). -
So
emis relative, not absolute likepx.
This means its actual value depends on context — i.e., where you use it.
⚠️ Why em can cause overflow
There are 3 main reasons:
1. Nested scaling effect
Each nested element inherits and multiplies the em value.
Even though you might expect 10em = 160px,
it actually becomes 320px because it’s relative to .container, not body.
๐ If you keep nesting elements using em, it quickly becomes bigger than expected, causing overflow.
2. Font-size scaling increases box size
If you use em for layout properties (like width, padding, or margin) and also increase font-size, those properties scale up too.
Example:
But if someone later changes:
Then width: 10em → 300px, and the element might now overflow its container.
3. Combining em with limited parent space
If the parent has a fixed width (e.g., 200px) but your child uses em based on a large font-size:
๐ฅ Boom — overflow! The child is wider than the parent.
๐ก How to avoid overflow
✅ Use rem (root em) for consistent sizing
1rem = font size of root <html> (usually 16px). It doesn’t multiply inside nested elements.
✅ Use percentage (%) for width if you want it to fit the parent.
✅ Use max-width: 100% to prevent elements from exceeding their container.
✅ Be careful mixing font scaling (em) with fixed container sizes.
When you use a value like width: 5em; (or font-size: 5em;, padding: 5em;, etc.), the em unit is relative to the font size of the element (or its parent).
So:
-
1em= current font size -
5em= 5 × current font size
For example:
✅ No overflow if the parent container is large enough.
But if your parent element has a small container width, or if the em unit grows too large (say font-size is 20px, so 5em = 100px), then:
-
The box may become wider than its parent, or
-
Text may overflow horizontally (especially if you also have padding/margin in
emunits).
Common reasons overflow happens with em
-
The element’s parent has a small width (e.g., inside a flexbox or grid cell).
-
The element’s
font-sizeis large, so5embecomes a large pixel value. -
Padding or margin is also in
em— making the box even bigger. -
You didn’t use
overflow: hiddenortext-overflow: ellipsisto control it.
How to fix it
You can try:
Or, use relative units like rem, %, or vw depending on your design.
Comments
Post a Comment