16

working on converting our company site over to something more responsive so reworking the css to use em's instead of the tried and true px.

The problem i'm running into is the inheritance of font-size and am looking for best practices for this issue.

This is how I'm solving the problem as of now.

jsfiddle for your viewing pleasure

HTML

<h3>Heading with a <a href="#">Link</a></h3>

<p>this is a paragraph with a <a href="#">Link</a> inside of it</p>
<a href="#">this is a link outside the paragraph</a>​

CSS

body {font:normal 100% sans-serif;}
p {font:normal 1.5em sans-serif; margin-bottom:.5em;}
h3 {font:bold 3em serif; margin-bottom:.5em; }
a:link {font-size:1.5em;}

p a, li a, h1 a, h2 a, h3 a, h4 a, h5 a,
h6 a, dl a, blockquote a, dt a, dd a, td a {
    font-size:1em !important;
}

I understand that em's are related to the parent font-size. so if I set p{font-size:1.5em;} and also set a:link{font-size:1.5em;} and my <a> is outside of my <p> then they will have the same relative size, great.

But if i then place an <a> inside a <p> the font size of the embedded <a> is now larger as it is 1.5em's larger than the <p>. To overcome this I set the last style with a string of p a, li a, h1 a,......{font-size:1em !important;}. Since a:link has a higher specificity than just p a i had to use !important (not a fan of !important), also i can't use font-size:inherit; as we have to support, dare i say it, ie6 (still have 15% traffic, we are biotech and some companies just refuse to upgrade).

So my question to you is this. Am I going about this the right way in tackling tags inside of tags to prevent my typography from breaking up? As soon as i wrote the last style i thought to myself, this can become a nightmare to maintain! I would like to use rem but the browser support isn't there for a portion of users.

How do you solve this problem in your own css and what would be a "best practices" approach to this.

4

3 回答 3

10

仅为块设置字体大小,例如标题和导航块。更改字体内联会导致混乱,所以不要为链接设置字体大小。相反,当需要时,设置包含导航链接的元素或其他元素ul的字体大小。div

一般来说,使用尽可能少的font-size设置,以尽量减少不必要的累积效应的风险。

笔记:

这根本与继承无关。当您font-size在一个元素上设置时,该元素肯定不会继承字体大小。这是关于em单位相对性质的影响。

a:link{font-size:1.5em;}例如,如果您已经设置,您可以轻松地为段落内的链接覆盖它,而无需使用!important. 你只需要更具体,这里的自然方式就是p a:link{font-size:1em;}.

于 2012-04-25T04:12:41.320 回答
4

您可能应该避免选择 just a,并且当您希望它们的大小与从容器继承的大小不同时,只需为它们添加更具体的选择器。我从不只为 更改字体大小a,而是在需要时更改其容器上的字体大小。同样,出于同样的原因,我避免为其他内联元素(例如 span、em、strong)添加字体大小。

于 2012-04-25T00:46:13.110 回答
1

我建议使用重置样式表,例如Eric Meyer 的 reset.css,它将字体设置为在所有元素上继承。然后设置默认(或“主要”)字体大小body并使用相对em单位设置所有其他元素的字体大小。

您“堆叠”相对字体大小的问题应该不是问题,因为您很少需要在包含文本以外的任何内容(例如标题标签)的元素上设置新字体。在例外情况下,相对字体大小应该是您网站的一项资产,例如在页脚区域中,所有文本都应该比网站默认值小一点。

在相对字体大小导致不需要的行为的(极少数)情况下,您始终可以这样做:

p
{
    font-size: 1.5em;
}

a
{
    font-size: 1.5em;
}

p a
{
    font-size: 1em;
}
于 2012-04-24T23:34:12.093 回答