0

I have a set of divs, like this

<div class="row header"></div>
<div class="row"></div>
<div class="row"></div>
<div class="row"></div>
<!-- add spacing here by adding margin to the row above -->
<div class="row header"></div>
<div class="row"></div>
<div class="row"></div>

As I cannot change markup, I wonder if I can add a space between .row and .row.header only without making any changes to other divs. Ideally, I need to add margin-bottom to every .row that is put before .row.header.

Is this possible with CSS at all without adding extra classes and hacks?

Sergei Basharov
  • 51,276
  • 73
  • 200
  • 335
  • 3
    can't you add `margin-top` to `.row.header`? – Tomasz Rup Mar 15 '17 at 12:46
  • @TomaszRup if all `.row.header` elements need such margins, then `margin-top` would suffice. The user specifically asks for "space between `.row` and `.row.header`". – Andrei V Mar 15 '17 at 12:52

5 Answers5

1

You could use the adjacent sibling selector:

.row + .row.header {
   margin-top: 20px;
}

This will only add a top margin to those .row.header elements which come after .row elements, making sure that the first .row.header element is not affected.

Andrei V
  • 7,306
  • 6
  • 44
  • 64
1

As it is indicated in this answer https://stackoverflow.com/a/1817801/2894798 there is no previous sibling selector in css, I would recommend to add margin top to .row.header

.row + .row.header{
margin-top:20px;
}
Community
  • 1
  • 1
Renzo Calla
  • 7,486
  • 2
  • 22
  • 37
0

It's easier to add top margin to divs with both row and header classes

.row.header {
 margin-top: 5px;
}
IiroP
  • 1,102
  • 2
  • 10
  • 14
0
If you want apply margin only where is the comment is written you can add css for that as follows

div.row:nth-of-type(4) {
   margin-bottom: 20px;
}

but if you want add margin to every 3'd div after .header, you need to apply css as follows

div.row:nth-of-type(4n) {
  margin-bottom: 20px;
}

Hope this will full fill your requirement.

Sudhakar Lahane
  • 137
  • 1
  • 2
  • 12
0

You can also use :not() selector if .row.header is first child of it's parent. For more info.

.row.header:not(:first-child) { 
    margin-top: 10px;
}