Greg Kennedy
Greg Kennedy

Reputation: 632

Changing CSS font-size alters other -em settings?

I'm trying to use em-units instead of px in a design, so that it scales well across screen / device / etc.

What I'm seeing is that when defining non-font things like "margin" or "padding" in terms of em-units, then when I alter the font-size within the same element, it changes the non-font elements. For example:

header {
  font-size: 1em;  # is default
  margin: 1em;     # will be 16pt
}

vs

div {
  font-size: 2.5em;
  margin: 1em;     # is now 40pt?
}

So my questions:

If it helps, I created a jsfiddle to test these things out: https://jsfiddle.net/0emnypou/

EDIT: It appears this may be a near-duplicate of: CSS "em" issue: avoid scalling to font-size of specific element

Upvotes: 1

Views: 4710

Answers (3)

P3t3r6
P3t3r6

Reputation: 1648

As for the first question: Yes, em units will (almost) always correspond to the current element's font-size, no matter the property you're using it on.

For a consistent "value", you could use rems , that stands for "root em", and that value will always be the same as the font-size that is set on your html.

You could also use vw and vh, which stands for "viewport width" and "viewport height"

em - Relative to the font-size of the element (2em means 2 times the size of the current font)

rem - Relative to font-size of the root element

vw - Relative to 1% of the width of the viewport

vh - Relative to 1% of the height of the viewport

vmin - Relative to 1% of viewport's smaller dimension

vmax - Relative to 1% of viewport's larger dimension

http://www.w3schools.com/cssref/css_units.asp

Upvotes: 2

David Alger
David Alger

Reputation: 21

I would suggest setting a base font size, say in and then use the rem unit (always refers back to the base font). I went to your jsfiddle and made these changes and it seems to work (only the changed in size).

`**body {font-size: 14pt;}**
header, article, footer {
  border: 1px solid;
  margin: **1rem**;
}

header {
  font-size: 2.5em;
  background-color: DarkTurquoise;
}

article {
  background-color: LightCyan;
 }

footer {
  font-size: **0.5rem**;
  background-color: DarkTurquoise;
}`

Upvotes: 2

Quotidian
Quotidian

Reputation: 2940

Yes, ems are dependent upon the font-size regardless of the element they are used with. 'em' is (was) tied to the width of a capital letter M.

'rem' on the other hand is the 'root M', meaning that the size is relative to the first declaration of the font-size. rems are particularly useful for the situation you describe.

Upvotes: 0

Related Questions