0

我正在使用 css2 在网站上实现 IE7 的一些修复。

所以我必须加上margin-top:30px一个margin-bottom:-30px标题<h2>,但我没有找到正确的选择器。

<div class="ui-content">
    <h2>Text</h2>
    <ul class="ui-listview">
        List Items
    </ul>
</div>

事实是,每次有 aH2后跟 aUL时,我都必须放置这两个属性,所以我想用 h2 和 ul 做一个选择器,但我不知道是哪一个......

谢谢帮助我

4

3 回答 3

0

您不能选择 h2s 后跟 uls,但您可以反过来做。例如

h2 + ul { /*your css to style the ul*/ }

所以你可以在 ul 上放置修​​复/负边距或其他任何东西?

于 2013-08-14T15:11:06.330 回答
0

这是一个只有 ie-7 的选择器:

IE 7 only
 *:first-child+html h2 {}

无论如何,我不推荐它,因为几乎没有人再使用这个浏览器了,所以你也不应该专门为它编程。

于 2013-08-14T15:11:59.217 回答
0

Everytime there is a H2 followed by a UL, I must put those two properties, so I wanted to do a selector with h2 and ul

As stated by @Spudley and @Coop, you can't select an element that is followed by another element (except rare cases with series of li or td or th and :nth-last-child() but it's more of a trick).
The closest thing you can do in pure CSS is testing if h2 is followed by (an)other element(s) or not, i.e. if it's not alone with :only-child pseudo.

From MDN:

The :only-child CSS pseudo-class represents any element which is the only child of its parent. This is the same as :first-child:last-child or :nth-child(1):nth-last-child(1), but with a lower specificity.

Support is IE9+ so if you want to style this element in IE7 and IE8 too (or in the precise case where it's followed by ul but not p or h3...), you'll need JavaScript or to add a class server-side and style this class.

.ui-content > h2:not(:only-child) {
    margin-top: 30px;
    margin-bottom: -30px;
}

EDIT:
You can also test if H2 is both the :first-child and the second-to-last child of its parent so it'll be styled if it's followed by whatever element but not if this second element has other siblings (third, fourth one, etc)

.ui-content > h2:first-child:nth-last-of-type(2) {
    margin-top: 30px;
    margin-bottom: -30px;
}

Simplest code would be ;)

<div class="ui-content">
    <h2 class="followed-by-list">Text</h2>
    <ul class="ui-listview">
        List Items
    </ul>
</div>

.followed-by-list {
    margin-top: 30px;
    margin-bottom: -30px;
}

Other trick that'd mean a complete overhaul of your project (say, for next project ;) ): never set a single margin-bottom to content elements (I mean h2, ul, p, etc. It's OK for div and below "blocks") and always set a margin-top to:

  • an element (general case) ex: p
  • if needed, an element coming after another like elt1 + p would have a certain margin-top, elt2 + p another one, etc
于 2013-08-14T16:52:00.423 回答