首页 > 解决方案 > 保证金 + ? = 弹性盒中的 100% 宽度

问题描述

我有一个 flexbox,里面的宽度和80vw内容是. 列中的所有项目在两侧都有边距。现在,他们很瘦,只占了一部分。检查它会在两侧显示大量空白。align-items: centerjustify-content: center28px80vw

我仍然想要文本居中之类的东西,但是选择框之类的东西应该占据容器的整个宽度(包括边距)。

我在这里读过一些东西,我尝试过设置width: 100%,但这不仅忽略了居中的css(将项目一直推到左边),而且忽略了边距,并且边距溢出了宽度容器。

最后,我尝试calc计算80vw - 28px了内部内容的宽度,但这做了一些奇怪的事情,只使用了一半的边距,其余的溢出了容器。

在此处输入图像描述

.outerContainer {
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  width: 100vw;
  height: 100vh;
  background-color: black;
}

.modalContainer {
  width: 80vw;
  background-color: white;
  z-index: 2;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
 
.content1 {
  margin: 20px 28px 10px 28px;
  font-size: 27px;
  line-height: 21px;
}

.content2 {
  margin: 10px 28px 20px 28px;
}
 
 
<html>
  <body>
    <div class="outerContainer">
      <div class="modalContainer">
        <div class="content1">
          Hello, World!
        </div>
        <div class="content2">
           <input type="text" />
        </div>
      </div>
    </div>
  </body>
</html>

标签: htmlcssflexbox

解决方案


您可以使用该calc函数使内容 div 的宽度为 100% 减去边距(添加到我在下面更改的行中的注释):

.outerContainer {
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  width: 100vw;
  height: 100vh;
  background-color: black;
}

.modalContainer {
  width: 80vw;
  background-color: white;
  z-index: 2;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
 
.content1 {
  margin: 20px 28px 10px 28px;
  font-size: 27px;
  line-height: 21px;
}

.content2 {
  margin: 10px 28px 20px 28px;
  width: calc(100% - 56px);    /* 100% width minus 28px x 2 */
}


.content2 > input {
    width:100%;              /* make input stretch full width */
}
<html>
  <body>
    <div class="outerContainer">
      <div class="modalContainer">
        <div class="content1">
          Hello, World!
        </div>
        <div class="content2">
           <input type="text" />
        </div>
      </div>
    </div>
  </body>
</html>


推荐阅读