html - nth-of-type 无法正常工作

标签 html css css-selectors

我有以下代码。

div img:nth-of-type(2n) {
    float: left;
}

div img:nth-of-type(2n+1) {
    float: right;
}
<div>
  <p>Some random text.</p>
  <p>
    <img src="http://placehold.it/20x20">
  </p>
  <p>Some random text.</p>
  <p>Some random text.</p>
  <p>
    <img src="http://placehold.it/20x20">
  </p>
  <p>Some random text.</p>
  <p>
    <img src="http://placehold.it/20x20">
  </p>
  <p>Some random text.</p>
</div>

我需要为偶数图像设置 float:left,为奇数图像设置 float:right。但在这两种情况下,都会触发第二个 css 规则。请帮助我。

最佳答案

您需要在 p 标签上使用 :nth-of-type 选择器。

这里的问题是段落元素是 div 的直接子元素。图像嵌套在段落标记内,而不是 div 的直接子级。所以它不会以 div 作为它的父级。


问题的 v1

div p:nth-of-type(2n) img { /* Select all even */
  float: left;
}
div p:nth-of-type(2n+1) img { /* Select all odd */
  float: right;
}
<div>
  <p>...</p>
  ...
  <p>
    <img src="http://placehold.it/20x20">
  </p>
  ...
  <p>
    <img src="http://placehold.it/20x20">
  </p>
  ...
  <p>
    <img src="http://placehold.it/20x20">
  </p>
  ...
</div>


问题的 v2

div p:nth-of-type(4n+2) img { /* Select 2,6,10 */
  float: left;
}
div p:nth-of-type(4n) img { /* Select 4,8 */
  float: right;
}
<div>
  <p>Some random text.</p>
  <p>
    <img src="http://placehold.it/20x20" alt="1">
  </p>
  <p>Some random text.</p>
  <p>
    <img src="http://placehold.it/20x20" alt="2">
  </p>
  <p>Some random text.</p>
  <p>
    <img src="http://placehold.it/20x20" alt="3">
  </p>
  <p>Some random text.</p>
  <p>
    <img src="http://placehold.it/20x20" alt="1">
  </p>
  <p>Some random text.</p>
  <p>
    <img src="http://placehold.it/20x20" alt="2">
  </p>
  <p>Some random text.</p>
  <p>
    <img src="http://placehold.it/20x20" alt="3">
  </p>
  <p>Some random text.</p>
</div>

关于html - nth-of-type 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32232998/

相关文章:

jquery - IE - 消失的导航

html - Chrome 如何知道我的地理位置?

php - 在没有插件的情况下使用内置在 thickbox 中的 wordpress

css - 如何防止选择图像的边

javascript - 附加到光标的故障 div

php - 单击时 Glyphicon 不旋转

javascript - 根据窗口大小更改 div 中的类 (jQuery/JS)

jquery - 判断 jQuery 是否没有找到任何元素

css - 你如何解决 IE 不支持 :after?

css - 将伪元素选择器作为 SASS 中的变量传递