仅当某个元素旁边存在某个元素时,才将样式应用于元素

2023-11-24

我正在使用<section>标签在几页上,但在一页上我使用<aside>前面带有<section> tag.

如果我有一个<section>紧接着是<aside>,我想对两者都应用宽度,并使部分向左浮动,侧面向右浮动。

基本上,如果我有一个<section> and <aside>我希望样式像这样工作:

section {
    width: 500px;
    float: left;
    padding: 8px;
}

aside {
    padding:8px; 
    width:400px;
    float:right;
}

如果我只有<section>我希望它是这样的:

section {
    padding: 8px;
}

有没有一种方法可以使用 CSS3 中的条件语句或伪类来执行此操作,而无需使用 JavaScript、自定义类或单独的 CSS 文件?


这仅在以下情况下有效<section/>出现在<aside/>:

<aside>content</aside>
<!-- if there is another node in between, use the '~' selector -->
<section>content</section>

在这种情况下你可以使用aside ~ section or aside + section:

section {
    padding: 8px;
}
aside + section {
    width: 500px;
    float: left;
}

在所有其他情况下,您都必须使用 JavaScript,因为这些选择器仅在一个方向上工作,即从上到下。

With CSS4 there might be a way using the Subject of a selector with Child combinator, but that's future. This selector was removed from the specification.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

仅当某个元素旁边存在某个元素时,才将样式应用于元素 的相关文章