nth-child 中奇数/偶数子元素的问题
- 作者: 网兼加569476996
- 来源: 51数据库
- 2022-10-20
问题描述
我有一个这样的网站:
<html xmlns="http://www.51sjk.com/Upload/Articles/1/0/331/331994_20221020121237554.jpg"><头><标题></标题><link rel="stylesheet" type="text/css" href="article_style.css"/></头><身体><div 类="节"><!--<h1>标题</h1>-->段落</div>段落</div>段落</div></div><div 类="节">段落</div>段落</div>段落</div></div></身体></html>这是 CSS:
div.section{边框:1px纯黑色;}div.section div:nth-child(偶数){颜色:绿色;}div.section div:nth-child(奇数){红色;}结果如下:
这没关系,因为在 each 部分中,奇数 div 为红色,偶数为绿色.但是当我在第一部分的开头添加标题时(示例中的注释代码)我得到了这个:
我不想那样.我希望像以前一样,但只是在第一部分有一个标题.所以首先是标题,然后是红色段落.
解决方案使用 nth-of-type 改为:
现场演示
div.section{边框:1px纯黑色;}div.section div:nth-of-type(偶数){颜色:绿色;}div.section div:nth-of-type(奇数){红色;}I have a web site like this:
<html xmlns="http://www.51sjk.com/Upload/Articles/1/0/331/331994_20221020121237554.jpg"> <head> <title></title> <link rel="stylesheet" type="text/css" href="article_style.css" /> </head> <body> <div class="section"> <!--<h1>header</h1>--> <div> paragraph </div> <div> paragraph </div> <div> paragraph </div> </div> <div class="section"> <div> paragraph </div> <div> paragraph </div> <div> paragraph </div> </div> </body> </html>and this is CSS:
div.section { border: 1px solid black; } div.section div:nth-child(even) { color: Green; } div.section div:nth-child(odd) { color: Red; }And this is the result:
This is OK because I get red for odd div and green for even in each section. But when I add header at the begginig of first section (commented code in sample) I get this:
I don't want that. I want the to have like before, but just with a header in first section. So at first header and then red paragraph.
解决方案Use nth-of-type instead:
Live Demo
div.section { border: 1px solid black; } div.section div:nth-of-type(even) { color: Green; } div.section div:nth-of-type(odd) { color: Red; }
推荐阅读热点文章
检查拆分键盘0
带有“上一个"的工具栏和“下一个"用于键盘输入AccessoryView0
Activity 启动时显示软键盘0
UIWebView 键盘 - 摆脱“上一个/下一个/完成"酒吧0
在 iOS7 中边缘滑动时,使键盘与 UIView 同步动画0
我的 iOS 应用程序中的键盘在 iPhone 6 上太高了.如何在 XCode 中调整键盘的分辨率?0
android:inputType="textEmailAddress";- '@' 键和 '.com' 键?0
禁用 iPhone 中键盘的方向0
Android 2.3 模拟器上的印地语键盘问题0
keyDown 没有被调用0
