非常简单的问题。我已经使用CSS有一段时间了,但很少在代码中使用+号。有人能解释一下什么时候最好使用它吗?我在谷歌上找不到任何东西...万分感谢...
非常容易的问题。我使用CSS已经有一段时间了,但是很少在我的代码中使用+号。有人能解释一下最佳使用时机吗?我在谷歌上没找到任何相关内容...非常感谢...我发现使用相邻兄弟选择器非常有用,当你想要对一系列元素中的第一个元素应用特殊样式时。例如,如果您想从其余部分不同地设置文章的第一段样式,您可以使用以下代码:
p {
/* styles for the first paragraph */
}
p + p {
/* styles for all other paragraphs */
}
在许多情况下,这可以替代使用 class="first"
。
编辑:对于这个特定的情况,使用first-child
伪类会更好一些,因为它被更广泛地支持。(感谢alex)
当您需要调整某些元素在彼此相邻时的位置时,您可能还想要进行调整。如果您有一个无序列表看起来很好,但是当它与段落相邻时需要较少的上部填充,则可以使用:
ul {
padding-top: 1em;
/* Default ul styling */
}
p + ul {
padding-top: 0;
/* special styling for lists that come after paragraphs */
}
这是一个相邻兄弟选择器
相邻兄弟选择器的语法为:E1 + E2,其中E2是选择器的主题。如果E1和E2在文档树中具有相同的父级并且E1紧接在E2之前(忽略非元素节点,如文本节点和注释),则选择器匹配。
简单来说,它可以像普通选择器一样选择元素,但同时还要求该元素在同一级别上有特定的前置元素。
例如,在下面的HTML中:
<p><div></div></p>
<span></span>
span
来选择它,但是如果您只想在它前面有 p
时影响某些样式的 span
,您可以使用 p + span
。请注意,此处不能使用 div + span
,因为 div
在不同的 "级别" 上。Also added in CSS2 was the direct adjacent combinator. For example, imagine you want to indent all paragraphs in a document except for ones immediately following a sub-heading (
<h2>
). The second rule below shows anh2
selector combined with a p selector using a plus sign as the combinator to indicate that the declaration applies only ifp
immediately followsh2
:
p { text-indent: 0.5in; } h2 + p { text-indent: 0; }
来源 - http://www.xml.com/pub/a/2003/06/18/css3-selectors.html
这篇文章介绍了CSS3选择器的功能和用法。CSS3选择器是一种强大的工具,可帮助开发人员更准确地选择需要样式化的HTML元素。通过使用各种选择器,如类选择器、ID选择器和属性选择器等,可以根据标记和属性选择元素,从而更精细地控制网页的外观和行为。
p:first-child { }
和级联效应不同吗? - alexfirst-child
由于跨浏览器原因实际上更好用。我总是忘记它的存在。谢谢! - derekerdmann:last-child
更好。 - alexp:first-child
不会像h2 + p
一样有效,因为你可能会在目标p
前面放置任何元素,比如标题。 - J Griffiths