Muhammad Umer
Muhammad Umer

Reputation: 18159

How do you stretch and center item using 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.

Upvotes: 11

Views: 4939

Answers (1)

Asons
Asons

Reputation: 87303

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>

Upvotes: 10

Related Questions