【问题标题】:Centering multiple items with display flex [duplicate]使用显示弹性居中多个项目[重复]
【发布时间】:2017-12-22 06:58:34
【问题描述】:

我想使用 justify-content: center 和 align-items: center 将 div 居中在页面的绝对中心,但 div 需要是页面的 100% 宽度和高度才能位于绝对中心。

当您在 div 的顶部或底部添加元素时,问题就出现了,这会降低我们想要居中的 div 的高度,并且不再位于绝对中心。

这里是页面https://jsfiddle.net/nybf8tjc/1 我可以添加

.typewriter{margin-top: -41px;}

要解决这个问题,但我觉得必须有更好的方法来解决这个问题。

【问题讨论】:

    标签: html css flexbox centering


    【解决方案1】:

    你可以通过这个简单的实现它。

    div.father {
      width: 100vw;
      height: 100vw;
      
      position: absolute;
      
      display: flex;
      align-items: center;
      justify-content: space-around;
     }
     
     div.father div.child {
      width: 400px;
      height: 250px;
      
      background-color: teal;
      
      position: relative;
      }
    <div class="father">
      <div class="child"></div> 
    </div>

    您也可以使用transform 属性:

    div.child {
      width: 400px;
      height: 250px;
      
      margin:0;
      padding: 0;
      
      
      background-color: teal;
      
      position: absolute;
      top: 50%;
      left: 50%;
      
      transform: translate(-50%, -50%);
    }

    这应该使您想要的容器居中。 看看https://css-tricks.com/snippets/css/a-guide-to-flexbox/

    【讨论】:

      【解决方案2】:

      您可以将.typewriter 设为绝对定位元素并添加通常的设置以使其居中,例如

      .typewriter {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        etc.
      }
      

      实际操作中:https://jsfiddle.net/de3rf65j/

      【讨论】:

        猜你喜欢
        • 2016-05-16
        • 2018-05-30
        • 1970-01-01
        • 2016-01-22
        • 2019-10-10
        • 1970-01-01
        • 2017-08-29
        • 2018-03-23
        • 2020-02-06
        相关资源
        最近更新 更多