Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
395 views
in Technique[技术] by (71.8m points)

css - How can I target a specific group of siblings in a flat hierarchy?

Assume you have this HTML:

<h1>Header 1</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<h1>Header 1</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<h1>Header 1</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>

Note that the hierarchy is flat.

Now try to select the "middle pair" of <p> elements. Is this possible? I really can't figure out how.

This selector only grabs the first <p> following the <h1>:

h1:nth-of-type(2) + p

But this selector grabs the correct pair of <p> elements plus all the following <p> elements that appear after the pair we want:

h1:nth-of-type(2) ~ p

Is it possible?

No JavaScript. No markup changing. Generic solution. Any number of <h1>s or <p>s are allowed, and the number two, in this case, is arbitrary.

I'm thinking maybe this is possible using some using the :not() selector, but I can't seem to figure it out. Kind of like selecting the "general siblings" and then excluding as necessary, or something similar.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Due to the way the general sibling combinator works, it is not possible to limit a selection of siblings to a specific range or group, even of consecutive siblings. Even the :not() selector won't be of any help here.

You will have to use JavaScript to target the right elements. jQuery's .nextUntil() method immediately springs to mind.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...