Usurer
Usurer

Reputation: 213

Why font-size in em's with important doesn't override font-size in px?

First things first - here is a fiddle, so you may scroll the code down: http://jsfiddle.net/Usurer/f5E7R/4/

I have a simple construction:

<div class='parent flex'>
    <div class='child-px'>
        abc
    </div>
    <div class='child-em'>
        abc
    </div>
</div>

supplied with stylesheet:

.flex { 
    font-size: .5em !important;
}

.parent {
    font-size: 1.5em;
}

.child-px {
    font-size: 20px;
}
.child-em {
    font-size: 2em;
}

My trouble is that .flex doesn't override .child-px. But why? Why? (I use Chrome v.33 if it matters)

---------------------------------

Now I've got it - child-em has changed font-size because, being em-based, it takes it from parent, not because it's font-size gets modified by .flex rule. And child-px doesn't care because its font-size is set in pixels.

Upvotes: 3

Views: 1076

Answers (2)

BoltClock
BoltClock

Reputation: 723538

That's because you've given .child-px its own font size. That alone is enough to prevent the font size of .flex from being inherited.

Even though you have the !important on .flex, the importance is only applied to that element. It doesn't affect any other elements, in particular it does not force descendants to inherit the value from it instead of using their own specified value.

Upvotes: 4

Hashem Qolami
Hashem Qolami

Reputation: 99484

This answer is based on your posted fiddle in which:

.flex { 
    font-size: 50% !important;
}

First of all, I should note that px is an absolute unit which unlike em, is not relative to the parent's font size. So it would be constant.

And in the demo you've provided, you'll get the value of font-size of the .child-em is pixels Because jQuery .css() method returns the computed style of elements.

From the jQuery doc:

.css( propertyName )
Get the computed style properties for the first element in the set of matched elements.

In this particular case, you have change the font size of the parent to 50% of the default (which is 16px in most web browsers) by .flex class name, and then double that value again for the .child-em element by 2em.

Therefor the returned value would be 16px.

Upvotes: 1

Related Questions