Reputation: 605
i have the following code on one of my websites:
body {
width: 1020px;
margin: 0 auto;
}
.box {
width: 500px;
float: left;
}
.clear {
clear: both;
height: 0;
font-size: 1px;
line-height: 0;
}
<body>
<p>Headline</p>
<div class="box">content</div>
<div class="box">content</div>
<div class="box">content</div>
<div class="clear"></div>
<p>Headline</p>
<div class="box">content</div>
<div class="box">content</div>
<div class="clear"></div>
<p>Headline</p>
<div class="box">content</div>
<div class="box">content</div>
<div class="box">content</div>
<div class="clear"></div>
</body>
I would like to add a margin-right of 10px to every box div that is on the left side so that there is a gap between the two divs that are next to each other.
I have tried to solve this with :nth-child() but it wont work because there are other elements like the p tags and the clearing elements in between.
Is there a way to solve this with just css?
I can not change the structure or the type of the elements by the way!
Upvotes: 0
Views: 40
Reputation: 2664
You can solve it by using nth-of-type()
selector if you can add a container
around each group:
body {
width: 1020px;
margin: 0 auto;
}
.box {
width: 500px;
float: left;
background: red;
}
.container div.box:nth-of-type(odd) {
margin-right: 10px;
}
.clear {
clear: both;
height: 0;
font-size: 1px;
line-height: 0;
}
<body>
<div class="container">
<p>Headline</p>
<div class="box">content</div>
<div class="box">content</div>
<div class="box">content</div>
<div class="clear"></div>
</div>
<div class="container">
<p>Headline</p>
<div class="box">content</div>
<div class="box">content</div>
<div class="clear"></div>
</div>
<div class="container">
<p>Headline</p>
<div class="box">content</div>
<div class="box">content</div>
<div class="box">content</div>
<div class="clear"></div>
</div>
</body>
Upvotes: 1
Reputation: 4106
Your HTML is not helping. Ideally, you would have a div wrapping all the divs with class .box. Something like:
.boxesWrapper {
display: flex;
justify-content: flex-start;
flex-wrap: wrap;
}
.box{
border: 1px dotted black;
margin-right: 10px;
width: 100px;
}
<body>
<p>Headline</p>
<div class="boxesWrapper">
<div class="box">content</div>
<div class="box">content</div>
<div class="box">content</div>
</div>
<p>Headline</p>
<div class="boxesWrapper">
<div class="box">content</div>
<div class="box">content</div>
</div>
<p>Headline</p>
<div class="boxesWrapper">
<div class="box">content</div>
<div class="box">content</div>
<div class="box">content</div>
</div>
</body>
Upvotes: 2