【问题标题】:Why do I cannot center elements if i scale them如果我缩放元素,为什么我不能居中
【发布时间】:2021-12-19 16:49:33
【问题描述】:

我正在使用它来使 CSS 中的内容居中:

.testclass {
display: flex;
justify-content: center;
}

但是当我想使用widthheight 缩放元素时,它不起作用并且我的元素没有居中。

像这样:

.testclass {
display: flex;
justify-content: center;
width: 200px;
height: 200px;
}

有什么问题?

【问题讨论】:

    标签: html css class


    【解决方案1】:

    如果您想要完全居中(水平垂直),您可以使用以下代码:

    .container {
      position: relative;
      width: 100%;
      height: 100vh;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    <div class="container">
      <div class="testclass">Content</div>
    </div>

    【讨论】:

      【解决方案2】:

      显示:弹性;和 justify-content: center; 适用于父元素。也就是说,特定父元素的子元素将居中,而不是父元素。

      居中 .testclass

      HTML

      <div class="parent">
          <div class="testclass"></div>
      </div>
      

      CSS

      .parent {
          background-color: red;
          display: flex;
          justify-content: center;
       }
       .testclass {
          background-color: green;
          width: 200px;
          height: 200px;
       }
      
          
      

      【讨论】:

        【解决方案3】:

        这看起来像预期的行为。

        请记住,在这种情况下,justify-content: center; 以容器内的内容为中心,而不是容器本身。

        编辑: 我添加了margin: 0 auto; 以使容器居中。

        #container1 {
          display: flex;
          justify-content: center;
          border: 1px solid red;
        }
        
        #container1 > div {
          border: 1px solid blue;
          background: yellow;
        }
        
        #container2 {
          display: flex;
          justify-content: center;
          border: 1px solid red;
          width: 200px;
          height: 200px;
          margin: 0 auto;
        }
        
        #container2 > div {
          border: 1px solid blue;
          background: yellow;
        }
        <div id="container1">
          <div>test 1</div>
        </div>
        <div id="container2">
          <div>test 2</div>
        </div>

        【讨论】:

        • 嗯好吧,但我应该如何使我的 div 居中?我的 div 只是一个输入文本字段和一个按钮。
        • @808hittin 查看编辑。
        猜你喜欢
        • 2021-11-08
        • 2014-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-09
        • 1970-01-01
        • 2013-10-17
        相关资源
        最近更新 更多