仅在元素旁边存在某个元素时才将样式应用于元素 [英] Apply style to element, only if a certain element exists next to it

查看:90
本文介绍了仅在元素旁边存在某个元素时才将样式应用于元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在几个页面上使用< section> 标记,但在一个页面上我使用< aside> 标记前面带有< section> 标记。

I'm using the <section> tag on several pages, but on ONE page I'm using an <aside> tag that is preceded by the <section> tag.

如果是我有< section> 后紧跟< aside> ,我想申请一个宽度两个并让部分向左浮动,然后向右浮动。

In the case that I have a <section> immediately followed by an <aside>, I would like to apply a width to both and have the section float left, and the aside float right.

基本上,如果我有一个< section> <搁置> 我希望样式能够像这样工作:

Basically, if I have a <section> and <aside> I want the style to work like this:

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

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

如果我只有< section> 我希望它像:

If I only have the <section> I want it to be like:

section {
    padding: 8px;
}

有没有办法可以用CSS3中的条件语句来做到这一点,或者是一个伪类,而不必使用JavaScript,自定义类或单独的CSS文件?

Is there a way I can do this with either a conditional statement in CSS3, or a pseudo-class, without having to use JavaScript, custom classes, or separate CSS files?

推荐答案

这只适用于< section /> 来自< aside />

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

在这种情况下你可以使用一边〜<$ code >或一边+部分

In that case you could use aside ~ section or aside + section:

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

在所有其他情况下,你将不得不使用JavaScript,因为这些选择器只能工作从一个方向,从上到下。

In all other cases you'll have to use JavaScript because these selectors only work in one direction, top to bottom.

使用CSS4可能有一种方法使用具有子组合子的选择器的主题,但那是未来。此选择器已从规范中删除。

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.

这篇关于仅在元素旁边存在某个元素时才将样式应用于元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆