当使用flexbox列时,如何保持居中div与最大宽度的折叠?

时间:2017-09-05 07:17:45

标签: html css flexbox

我有3个div垂直堆放在容器中。我希望中间div居中,但继续尽可能多地水平扩展但小于最大宽度。就像普通的div一样,max-width不涉及flexbox。

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>

2 个答案:

答案 0 :(得分:3)

设置align-self: center;以使您的div居中并添加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>

答案 1 :(得分:2)

您可能想要使用margin-left和margin-right并将它们设置为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;
}