I have this layout and I want to be able to add a margin around every element but without changing the widths of each element.
I know that, for example with the header
, I am able to apply a margin: 10px;
(let's focus on the left and right margin) and a width: calc(100% - 20px)
which takes away 20px from the 100% to account for the margin.
Question:
Is there a way to do this without changing the width?
So I can keep the width 100% and not have to worry about how much margin I apply to the elements?
You can play with flex-grow
. In your case you have width defined in this way: 20% + 60% + 20%
which is 20% + 3*20% + 20%
so we have factors like that 1 + 3 + 1
. So use these factors to setup flex-grow
then you can easily add margin like you want.
* {
box-sizing: border-box;
}
body,
html {
height: 100%;
width: 100%;
margin: 0;
}
body {
background: #333D4E;
}
/* Main */
main {
display: flex;
flex-direction: row;
width: 100%;
text-align: center;
}
article {
flex-grow: 3;
min-height: 800px;
background: #EDF0F1;
border-radius: 5px;
margin: 0 20px;
}
nav {
flex-grow: 1;
order: -1;
min-height: 800px;
background: #9AA4A6;
border-radius: 5px;
}
aside {
flex-grow: 1;
order: 1;
min-height: 800px;
background: #6295D6;
border-radius: 5px;
}
<main>
<article>Main Content</article>
<nav>Side Nav</nav>
<aside>Aside</aside>
</main>
The same apply to a single element:
body {
margin:0;
display:flex;
}
.container {
min-height:200px;
flex-grow:1;
margin:0 25px;
background:red;
}
<div class="container">
</div>
So the trick is to find the correct flex-grow
value to use.