看看这个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;
}

我希望框像块元素一样展开,但不要超出最大宽度,并且仍然居中。

如果我将align-items设置为在 body 上拉伸(stretch),则box会扩展,但会向左对齐,如果将margin自动或align-items设置为居中,则box将停止尝试尽可能多地填充宽度。

我只是希望将框扩展到800像素,但是当窗口大小更改时,其宽度也会减小,就像任何常规块元素的宽度默认情况下一样。

使用flexbox的全部原因是要让盒子也覆盖剩余的高度。

最佳答案

给出box width: 100%;margin: 0 auto;box-sizing: border-box;,以便在其宽度中包含填充

Updated codepen

堆栈片段

* {
  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>

关于html - 如何使用Flexbox拉伸(stretch)和居中放置物品?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43303138/

10-14 14:35
查看更多