What does the “+” (plus sign) CSS selector mean?

2018-12-31 03:18发布

For example:

p + p {
  /* Some declarations */
}

I don't know what the + means. What's the difference between this and just defining a style for p without + p?

11条回答
高级女魔头
2楼-- · 2018-12-31 04:04

This selector means that the style applies only to paragraphs directly following another paragraph.
A plain p selector would apply the style to every paragraph in the page.

See adjacent selectors on W3.org.


This will only work on IE7 or above. In IE6, the style will not be applied to any elements. This also goes for the > combinator, by the way.

See also Microsoft's overview for CSS compatibility in Internet Explorer.

查看更多
君临天下
3楼-- · 2018-12-31 04:04

It's the Adjacent sibling selector.

From Splash of Style blog.

To define a CSS adjacent selector, the plus sign is used.

h1+p {color:blue;}

The above CSS code will format the first paragraph after (not inside) any h1 headings as blue.

h1>p selects any p element that is a direct (first generation) child (inside) of an h1 element.

  • h1>p matches <h1> <p></p> </h1> (<p> inside <h1>)

h1+p will select the first p element that is a sibling (at the same level of the dom) as an h1 element.

  • h1+p matches <h1></h1> <p><p/> (<p> next to/after <h1>)
查看更多
余生无你
4楼-- · 2018-12-31 04:05

The + sign means select an adjacent sibling

Example:

CSS

p + p
{
   font-weight: bold;
} 

HTML

The style will apply from the second <p>

<div>
   <p></p>
   <p></p>
</div>

Example

See this Fiddle and you will understand it forever: http://jsfiddle.net/7c05m7tv/ (Another Fiddle: http://jsfiddle.net/7c05m7tv/70/)


Browser Support

Adjacent-sibling selectors are supported in Internet Explorer 5.x Macintosh. They are also supported in the Netscape 6 preview release 1 for all the myriad platforms for which it's available, and in preview release 3 of Opera 4 for Windows. There are bugs in the handling of adjacent-sibling selectors in IE5 for Windows, and Opera 3 for Windows.

Good to know: Internet Explorer 7 doesn't update the style correctly when an element is dynamically placed before an element that matched the selector. In Internet Explorer 8, if an element is inserted dynamically by clicking on a link the first-child style isn't applied until the link loses focus.


Learn more

查看更多
君临天下
5楼-- · 2018-12-31 04:06

It would match any element p that's immediately adjacent to an element 'p'. See: http://www.w3.org/TR/CSS2/selector.html

查看更多
素衣白纱
6楼-- · 2018-12-31 04:06

It selects the next paragraph and indents the beginning of the paragraph from the left just as you might in Microsoft Word.

查看更多
登录 后发表回答