Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flexbox div goes off screen on small screen

Tags:

html

css

flexbox

Code first:

html {
  display:flex;
  width:100%;
  height:100%;
}

body {
 display:flex;
  flex:1;
}

.container {
  display:flex;
  flex:1;
  overflow-y:auto;
  flex-direction:column;
  justify-content:center;
  align-items:center;
}

.block1 {
  justify-content:center;
  background-color:green;
  display:flex;
  width:300px;
  min-height:150px;
}

.block2 {
  background-color:blue;
  display:flex;
  min-height:300px;
    width:500px;

}
<div class="container">
<div class="block1">
  <img src="https://tse2.mm.bing.net/th?id=OIP.M252f960f4a4f32c22914d8d87623f066o0&pid=15.1">
</div>
<div class="block2"></div>
</div>

I have two blocks in a container. I want them centered on the screen. The issue is when the screen height is small, I have a scrollbar that appear but the first block have a part that go offscreen (is invisible)

To reproduce, decrease the height of the jsfiddle preview window. You will understand what I mean by going off screen.

The expected behavior is to let the scroll bar appear and keep the div visible.

I tried by setting flex-shrink to 0 on every element but it isn't working...

like image 523
Adavo Avatar asked Oct 13 '16 09:10

Adavo


1 Answers

You can make use of Flexbox's auto margins.

  1. Remove justify-content: center from .container.
  2. Add margin-top: auto to .block1.
  3. Add margin-bottom: auto to .block2.

html {
  display:flex;
  width:100%;
  height:100%;
}

body {
 display:flex;
  flex:1;
}

.container {
  display:flex;
  flex:1;
  overflow-y:auto;
  flex-direction:column;
  align-items:center;
}

.block1 {
  justify-content:center;
  background-color:green;
  display:flex;
  width:300px;
  min-height:150px;
  margin-top: auto;
}

.block2 {
  background-color:blue;
  display:flex;
  min-height:300px;
  width:500px;
  margin-bottom: auto;
}
<div class="container">
<div class="block1">
  <img src="https://tse2.mm.bing.net/th?id=OIP.M252f960f4a4f32c22914d8d87623f066o0&pid=15.1">
</div>
<div class="block2"></div>
</div>
like image 188
darrylyeo Avatar answered Sep 19 '22 19:09

darrylyeo