How do I use pseudo-classes to select all children except first and last?

南楼画角 提交于 2019-12-11 02:45:15

问题


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



来源:https://stackoverflow.com/questions/9067792/how-do-i-use-pseudo-classes-to-select-all-children-except-first-and-last

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!