如何用CSS选中各组连续p.vrt元素的首个与末尾元素
选中连续分组内的首个与末尾p.vrt元素
当前使用的:nth-child(1 of p.vrt)和:nth-last-child(1 of p.vrt)会选中容器内全局的第一个和最后一个p.vrt元素,无法满足“选中每组连续p.vrt元素首尾”的需求——比如示例中会错误选中跨分组的元素,而非每组的首尾。
正确的CSS解决方案
替换原有首尾元素选择器,使用以下规则即可精准匹配每组连续p.vrt的首尾:
div { width: 300px; text-align: center; } p:not(.vrt) { text-align: left; } p.vrt { writing-mode: vertical-rl; display: inline-block; } /* 选中每组连续p.vrt的首个元素 */ div > p.vrt:first-child, div > p:not(.vrt) + p.vrt { margin-left: 0; } /* 选中每组连续p.vrt的末尾元素 */ div > p.vrt:last-child, div > p.vrt:not(:has(+ p.vrt)) { margin-right: 0; }
选择器逻辑说明
- 选中首个元素:
div > p.vrt:first-child:处理容器开头就是p.vrt的场景(第一组从容器起始位置开始)div > p:not(.vrt) + p.vrt:选中紧跟在非vrt类p元素后的第一个p.vrt,匹配每组连续p.vrt的起始位置
- 选中末尾元素:
div > p.vrt:last-child:处理容器结尾是p.vrt的场景(最后一组到容器末尾结束)div > p.vrt:not(:has(+ p.vrt)):选中后面没有紧跟p.vrt元素的p.vrt,匹配每组连续p.vrt的结束位置(:has选择器目前主流现代浏览器均已支持)
效果验证
针对你提供的HTML结构:
<div> <p>This is some sample text which is not meant to be read.</p> <p class="vrt">幾見本言葉</p> <p class="vrt">幾見本言葉</p> <p class="vrt">幾見本言葉</p> <p>This is some sample text which is not meant to be read.</p> <p class="vrt">幾見本言葉</p> </div>
修改后的CSS会正确选中:
- 第一组连续p.vrt的第1个(应用
margin-left: 0)和第3个(应用margin-right: 0) - 第二组唯一的p.vrt(同时匹配首尾规则,
margin-left和margin-right均为0)
内容的提问来源于stack exchange,提问作者Andrew Foulds
相关产品推荐
相关产品推荐

