0

I'm trying to vertically stack 3 DIVs, where each DIV takes around one third (33.33%) of the vertical area, so eventually, all three of them will fill the entire screen. But at the same time, I want a margin of 8px around all three of them without having a scroll-bar. Like in the following image...

example image

So in the end, I have a responsive layout, separated vertically into 3 sections, with a margin around all of them (With no scroll-bar appearing)

This is my current code:

body {
  margin: 8px;
  background: red;
}

.header {
  width:  100%;
  height: 33.33%;
  background: #fff;
}

.content {
  width:  100%;
  height: 33.33%;
  background: #ccc;
}

.footer {
  width: 100%;
  height: 33.33%;
  background: #777;
}
<div class="container">
  <div class="header">
    header
  </div>

  <div class="content">
    content
  </div>

  <div class="footer">
    footer
  </div>
</div>

For some reason, this code works fine in (https://liveweave.com/), but it doesn't work in the chrome browser

Mhd Alaa Alhaj
  • 2,438
  • 1
  • 11
  • 18

1 Answers1

2

You can use flexbox for this - note the use of the flex-direction column - this allows you to create your stacked divs vertically.

This gives your 3 div layout.with each div taking up the third of the height of the viewport minus the 16px (from the 8px top and bottom), by removing the 16px - you will not get the scrollbar.

Since you are using flex - you do not have to specify the 33.334% - each div simply grows to fill the space and since there are 3 - with each having the flex-grow styling - they equate to thirds of the viewport height.

body, html {
  padding:0;
  margin: 0;
}
.container {
  padding: 8px;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 16px);
  background: red;
}

.header {
  background: #fff;
  flex-grow: 1;
  display: block
}

.content {
  width:  100%;
  background: #ccc; 
  flex-grow: 1;
  display: block
}

.footer {
  background: #777;
  flex-grow: 1;
  display: block
}
<div class="container">
  <div class="header">
    header
  </div>

  <div class="content">
    content
  </div>

  <div class="footer">
    footer
  </div>
</div>

body, html {
  padding:0;
  margin: 0;
}

.container {
  padding: 8px;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 16px);
  background: red;
}

header {
  background: #fff;
  flex-grow: 1;
  display: block
}

main {
  width:  100%;
  background: #ccc; 
  flex-grow: 1;
  display: block
}

footer {
  background: #777;
  flex-grow: 1;
  display: block
}
<div class="container">
  <header>
    header content
  </header>

  <main>
    content
  </main>

  <footer>
    footer content
  </footer>
</div>
gavgrif
  • 15,194
  • 2
  • 25
  • 27
  • Thanks for accepting - just note I was editing and you may not have seen my suggestion to use hte
    ...
    ,
    ...
    and
    ...
    elements. These are the correct semantic elements in HTML 5 for your page layout.
    – gavgrif Jan 11 '21 at 13:17