【问题标题】:Stretch display flex or table inner divs along parent with centered texts使用居中文本沿父级拉伸显示 flex 或表格内部 div
【发布时间】:2019-06-14 10:26:03
【问题描述】:

我想创建一个具有固定 html 结构的响应式页面,这样我就可以调整 css。我想创建具有垂直和水平居中文本的行。 div 应该完全跨越父 div。

我的 HTML...

<body>
  <div class="parent">
    <div class="d1">
      one
    </div>
    <div class="d2">
      two
    </div>
    <div class="d3">
      three
    </div>
  </div>
</body>

我的 CSS...

body {
  background-color: lightyellow;
  height: 100%;
  width: 100%;
  margin: 0px;
}
.parent {
  background-color: lightblue;
  height: 100%;
}
.d1, .d2, .d3 {
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  height: 100px;
}
.d2 {
  background-color: lightgreen;
}

但是在这里我将 d1、d2 和 d3 设置为 100px 的高度,而不是父 div 的 100%。此处示例:https://jsfiddle.net/bLf2sxq0/

我的第二个想法是使用 display: table 作为父级,这会为子级生成表格行,但我最终会遇到相同的拉伸问题,而且文本不是垂直居中的。这里的 css 应该是这样的......

body {
  background-color: lightyellow;
  height: 100%;
  width: 100%;
  margin: 0px;
}
.parent {
  width: 100%;
  height: 100%;
  display: table;
  background-color: lightblue;
}
.d1, .d2, .d3 {
  text-align: center;
  height: 100px;
}
.d2 {
  background-color: lightgreen;
}

此处示例:https://jsfiddle.net/qmbzkwr2/

有没有办法沿父级垂直拉伸 div 并保持文本在 div 内垂直和水平居中?所以我不会有宽度 100px 但类似 calc(100%/3) 或任何其他解决方案来做到这一点?或者也许通过使用 flex grow 选项?最简单的方法就是这样做:)

感谢您的帮助!

【问题讨论】:

    标签: html css flexbox alignment vertical-alignment


    【解决方案1】:

    你在正确的轨道上。使用 flexbox 垂直且均匀地拉伸和填充项目。记得将父容器(例如body、html)设置为height: 100%

    从这里开始,如果您想控制某些项目,请在任何单个项目上使用 flex,例如在 .d2 类上使用 flex: 1 1 300px

    Codepen

    body, html {
      height: 100%;
    }
    
    .parent {
       background-color: lightblue;
       height: 100%;
       
       display: flex;
       flex-direction: column;
     }
    
     .d1, .d2, .d3 {
       display: flex;
       align-items: center;
       justify-content: center;
       flex: 1;
     }
    
     .d2 {
       background-color: lightgreen;
     }
      <div class="parent">
        
        <div class="d1">
          <div class="d11">
            one
          </div>
        </div>
        
        <div class="d2">
          two
        </div>
        
        <div class="d3">
          three
        </div>
        
      </div>

    【讨论】:

      猜你喜欢
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-13
      相关资源
      最近更新 更多