Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you stretch and center item using Flexbox?

Tags:

html

css

flexbox

Take a look at this https://codepen.io/techsin/pen/JWQgoM

//html
<div class="nav"> a \ b \ c</div>
<div class="box"> no text</div>

//css
body {
  display: flex;
  flex-direction: column;
  align-items: center;
  align-content: stretch;
}

.box {
  max-width: 800px;
  padding: 30px;
  background-color: gray;
  flex-grow:1; 
}


.nav {
  padding: 30px;
  background-color: purple;
  text-align: center;
  color: #fff;
}

I want box to expand like a block element, but not expand beyond max width, and still be centered.

If I set align-items to stretch on body then box do expands but it gets aligned to left, if set margin auto Or align-items to center, then box stops trying to fill as much as possible width wise.

I simply want box to expand to 800 pixels, but when windows size changes its width also goes down, just like how any regular block element's width would act by default.

Whole reason to use flexbox is to have box also cover remaining height.

like image 623
Muhammad Umer Avatar asked Apr 09 '17 04:04

Muhammad Umer


1 Answers

Give the box width: 100%;, margin: 0 auto; and box-sizing: border-box;, so the padding gets included in its width

Updated codepen

Stack snippet

* {
  padding: 0;
  margin: 0;
}

html, body {
  height: 100%;
}

body {
  display: flex;
  flex-direction: column;
}

.box {
  max-width: 800px;
  width: 100%;
  padding: 30px;
  background-color: gray;
  flex-grow:1;
  margin: 0 auto;
  box-sizing: border-box;
}

.nav {
  padding: 30px;
  background-color: purple;
  text-align: center;
  color: #fff;
}
<div class="nav"> a \ b \ c</div>
<div class="box"> no text</div>
like image 101
Asons Avatar answered Oct 22 '22 04:10

Asons