2

Given the example below, each row needs to have three text columns, i.e. three sentences, where the middle ones also need to have a background-color. Is it possible to do that with the nth-child() selector?

p {
  display: inline-block;
  width: 30%;
}

p:nth-child(2n+0) {
  background: red;
}
<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>
<p>The fifth paragraph.</p>
<p>The sixth paragraph.</p>
<p>The seventh paragraph.</p>
<p>The eight paragraph.</p>
<p>The ninth paragraph.</p>

1
  • 1
    Hello @Bst_coder Try this p:nth-child(3n+2) { background: red; } Commented Jan 14, 2019 at 7:55

3 Answers 3

5

You could use

p:nth-child(3n+2) {
  background: red;
}
Sign up to request clarification or add additional context in comments.

Comments

2

use flex to wrap and to p use p:nth-child(3n+2)

.wrap{
display:flex;
flex-wrap: wrap;
}

p {
flex: 1 0 33%;
}

   p:nth-child(3n+2){
  background: red;
}
<div class="wrap">
<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>
<p>The fifth paragraph.</p>
<p>The sixth paragraph.</p>
<p>The seventh paragraph.</p>
<p>The eight paragraph.</p>
<p>The ninth paragraph.</p>
</div>

Comments

0

Whilst it can be done - i would not do it this way. But in the interest of getting the styling that you want - if the number and alignment is always as you have it here then you can do it as follows.

This will give the rows of p elements and will give a background color on the middle p element in each row - thereby creating a "column" effect. but you really should use a better HTML structure.

p {
display:inline-block;
width:30%;
}

p:nth-child(2), 
p:nth-child(5), 
p:nth-child(8) {
  background: red;
}
<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>
<p>The fifth paragraph.</p>
<p>The sixth paragraph.</p>
<p>The seventh paragraph.</p>
<p>The eight paragraph.</p>
<p>The ninth paragraph.</p>

1 Comment

You should also give an example of the better HTML structure that you hint at.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.