如何制作居中且宽度动态的弹性盒子?

3
这段标记应该生成一个高度为30像素、宽度为600像素的居中框。但实际上,它会使框缩小到没有宽度(或者如果有内容,则缩小到最小内容宽度)。想知道如何使居中框保持600像素宽并在较小的窗口大小下响应。

* {
  position: relative;
  box-sizing: border-box;
}

html, body {
  height: 100%;
  overflow: hidden;
}

div {
  display: flex;
}

body > div {
  align-items: center;
  -webkit-box-pack: center;
  -webkit-justify-content: center;
  justify-content: center;
  border: 1px solid orange;
}

body > div > div {
  max-width: 600px;
  border: 1px solid black;
}

body > div > div > div {
  border: 1px solid blue;
  background: red;
  height: 30px;
}
<div>
  <div>
    <div></div>
  </div>
</div>

3个回答

3
请尝试以下方法。给 body > div > divbody > div > div > div 类添加 width:100%

* {
  position: relative;
  box-sizing: border-box;
}

html, body {
  height: 100%;
  overflow: hidden;
}

div {
  display: flex;
}

body > div {
  align-items: center;
  -webkit-box-pack: center;
  -webkit-justify-content: center;
  justify-content: center;
  border: 1px solid orange;
}

body > div > div {
  max-width: 600px;
  border: 1px solid black;
  width:100%;
}

body > div > div > div {
  border: 1px solid blue;
  background: red;
  height: 30px;
  width:100%;
}
<div>
  <div>
    <div></div>
  </div>
</div>


2

这是flex项目的默认行为,它的宽度与其内容一样宽,类似于内联块。

原因在于其默认值flex-grow,其值为0,表示不填充剩余空间。

flex-grow: 1添加到每个应填充其父级的flex项目的级别中。

* {
  position: relative;
  box-sizing: border-box;
}

html, body {
  height: 100%;
  overflow: hidden;
}

div {
  display: flex;
}

body > div {
  align-items: center;
  -webkit-box-pack: center;
  -webkit-justify-content: center;
  justify-content: center;
  border: 1px solid orange;
}

body > div > div {
  max-width: 600px;
  border: 1px solid black;
  flex-grow: 1;                    /*  added  */
}

body > div > div > div {
  border: 1px solid blue;
  background: red;
  height: 30px;
  flex-grow: 1;                    /*  added  */
}
<div>
  <div>
    <div></div>
  </div>
</div>


0

请允许我将代码简化为其基本组件。您有一个设置为display:flexdiv.container。在其中,您有一个希望根据弹性参数进行调整的div。内部的

根据其容器设置为增长和收缩:

flex: 1 1 auto; /* shorthand for flex-grow, flex-shrink, flex-basis */

此外,它还设置了max-width:600px并使用margin-leftmargin-right居中于页面上。我相信这个结构符合您的要求。

div.container {
  display: flex;
  border: 1px solid orange;
}

div.container div {
  flex: 1 1 auto;
  border: 1px solid blue;
  background: red;
  height: 30px;
  margin: 0 auto 0 auto;
  max-width: 600px;
}
<div class="container">
  <div></div>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接