How do I use pseudo-classes to select all children

2019-07-18 09:17发布

问题:

In CSS, for the example shown below, how can I make it such that the styles get applied to all paragraphs, except for the first and the last paragraph?

<div class="entry">
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
</div>

I've tried the following to exclude the first paragraph, but that doesn't work:

div.entry p:nth-child(n+1) {
    /* ... */
}

I've also tried nth-of-type() and not(), but couldn't get them to work the way I thought they would.

Edit: I've decided to wrap all the <p>s which I want to apply the style to in a <div>. I've accepted bozdoz answer, because it came the closest to solving the original problem (even though it solved only half of it).

回答1:

Updated answer:

Use both :not(:first-child) and :not(:last-child)

div.entry p:not(:first-child):not(:last-child)

See updated JSFiddle.



回答2:

I know I am late to the game on this, but I thought I would just add this for any future viewers.

div.entry p:not(:first-child):not(:last-child)



回答3:

I just stumbled across something that might answer your question:

To represent all h2 children of an XHTML body except the first and last, one could use the following selector:

body > h2:nth-of-type(n+2):nth-last-of-type(n+2)

W3C - CSS3-Selectors