Override em font-size when elements are nested

2019-02-23 16:42发布

问题:

How do you override the font-size property when you have nested elements? Using !important doesn't seem to have any effect.

div {
    font-size:6em;  
}
p {
    font-size:1em !important;
}
span {

    font-size:1em;
}

-

<html>
<body>
    <div><span>span</span><p>paragraph</p></div>
</body>
</html>​

http://jsfiddle.net/dvUTQ/

回答1:

Em's are relative sizes to their parent elements.

http://jsfiddle.net/dvUTQ/3/

div#small {
  font-size:2em; 
}
div#big {
  font-size:6em;
}
p {
  font-size:.5em; /* effective sizes: big: 3em, small: 1em */
}
span {
  font-size:2em; /* effective sizes: big: 12em, small: 4em */
}

Setting a child element to 1em just makes it the same size as its parent. .5em on p in this case would effectively make it 3em.

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



回答2:

In addition to dmzza's answer: The !important rule only has effect when you have selectors in your style sheet with conflicting specificity.

In your case there was no conflict, so the !important rule couldn't have any effect.

When you have conflicting specificity it is always better to create a more specific selector for the exception.



回答3:

You could use the CSS3 rem unit, which is relative to the root, not the parent. I've been stuck in this same dilema as the project I'm working on has so many nested elements that the em is not reliable.

You can find more information here http://snook.ca/archives/html_and_css/font-size-with-rem.

The only issue is fallback browser support for IE8 and below. You still need to provide a pixel size before declaring the rem size. Despite this extra coding, it may still be worth looking into.