Muhammad Umer
Muhammad Umer

Reputation: 18097

how do i keep centered div with max-width from collapsing when using flexbox column?

I have 3 divs vertically stacked in container. I want middle div to be centered but continue expanding horizontally as much as it can but less than max-width. Just like normal div would with max-width without flexbox involved.

https://codepen.io/anon/pen/XaQXOW

css

.cont {
  display: flex;
  flex-direction: column;
}

.b {
  max-width: 500px;
  background-color: cyan;
}
.a, .b, .c {
  border: 1px solid #000;
  height: 100px;
}

html

<div class="cont">
  <div class="a"></div>
  <div class="b"></div>
  <div class="c"></div>
</div>

Upvotes: 6

Views: 3676

Answers (2)

MMRahman
MMRahman

Reputation: 319

You may want to use margin-left and margin-right and set them auto

JSFIDDLE

HTML

<div class="cont">
 <div class="a"></div>
 <div class="b"></div>
 <div class="c"></div>
</div>

CSS

.cont {
display: flex;
flex-direction: column;
}

.b {
  background-color: cyan; 
  max-width: 500px; 
  margin-left: auto; 
  margin-right: auto;
  width: 100%; 
}
.a, .b, .c {
 border: 1px solid #000;
 height: 100px;
}

Upvotes: 5

Huelfe
Huelfe

Reputation: 1836

Set align-self: center; to center your div and add width: 100%:

.cont {
  display: flex;
  flex-direction: column;
}

.b {
  max-width: 500px;
  background-color: cyan;
  align-self: center;
  width: 100%;
  box-sizing: border-box;
}

.a, .b, .c {
  border: 1px solid #000;
  height: 100px;
}
<div class="cont">
  <div class="a"></div>
  <div class="b"></div>
  <div class="c"></div>
</div>

Upvotes: 11

Related Questions