0

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?

Jos van Weesel
  • 2,128
  • 2
  • 12
  • 27
  • Margins and width/height are like oil and water. They don't blend. So the answer to your question is "no". However, if you're open to other spacing options, there are many. Here's a start: https://stackoverflow.com/q/45057867/3597276 – Michael Benjamin May 15 '18 at 16:02
  • you could use a border instead using `box-sizing: border-box`. Or a inner outline or an inset box-shadow – Fabrizio Calderan May 15 '18 at 16:07
  • 1
    In your case you can't do it without changing width but you can do it by removing width. Divs will fit to available space, considering margins. – Fab May 15 '18 at 16:08
  • @rpm192 Have you read the question at all? If you go to my example you can see I am using Flexbox already. I explained that I do not want to change the percentages of each element's width, as well. – Jos van Weesel May 15 '18 at 17:40

1 Answers1

1

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.

Temani Afif
  • 245,468
  • 26
  • 309
  • 415