Here I have 2 rows and 2 columns in each row. I want the yellow blocks to have a margin and take all the available space in the column besides the margin. But as you can see, the margin completely misaligns the yellow content.
.row {
background: green;
}
.col {
background: red;
border: 1px solid blue;
height: 60px;
}
.content-margin {
margin: 10px;
background: yellow;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<div >
<div >
<div >
<div ></div>
</div>
<div >
<div ></div>
</div>
</div>
<div >
<div >
<div ></div>
</div>
<div >
<div ></div>
</div>
</div>
</div>
The result I want is similar to this:
Is there any way to achieve that by adding margin to the yellow block?
NOTE: I know I can achieve that by adding padding to the COL itself, but that's no good for my real world use case.
https://jsfiddle.net/39zp4tc0/
CodePudding user response:
Just use a padding on the parent (col) instead of a margin on the child:
.row {
background: green;
}
.col {
background: red;
border: 1px solid blue;
height: 60px;
padding: 10px
}
.content-margin {
background: yellow;
}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
<div >
<div >
<div >
<div ></div>
</div>
<div >
<div ></div>
</div>
</div>
<div >
<div >
<div ></div>
</div>
<div >
<div ></div>
</div>
</div>
</div>
I do recommend using margin to positioning and padding for that spaces between components. You can use margin: auto in combination with display flex to make a div in a specific position. You can view more information on https://css-tricks.com/snippets/css/a-guide-to-flexbox/
CodePudding user response:
Change the height of the yellow column to 60% with margin: 12px 0; Try this:
.row {
background: green;
}
.col {
background: red;
border: 1px solid blue;
height: 60px;
}
.content-margin {
margin: 12px 0;
background: yellow;
}
.h-60 {
height: 60%;
}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
<div >
<div >
<div >
<div ></div>
</div>
<div >
<div ></div>
</div>
</div>
<div >
<div >
<div ></div>
</div>
<div >
<div ></div>
</div>
</div>
</div>