Nikita Gorshkov
Nikita Gorshkov

Reputation: 1697

nth-of-type does not work properly

I have the following code.

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>

I need to set the float:left for even images and float:right for odd. But in both cases, the second css-rule is triggered. Help me please.

Upvotes: 0

Views: 237

Answers (2)

m4n0
m4n0

Reputation: 32255

You will need to use the :nth-of-type selector on p tag.

Problem here is that the paragraph element is the immediate children of div. The image is nested inside a paragraph tag and not the immediate children of div. So it will not take div as its parent.


v1 of the question

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 of the question

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>

Upvotes: 1

gview
gview

Reputation: 15361

Why not:

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

div img:nth-of-type(even) {
    float: right;
}

Upvotes: 0

Related Questions