【问题标题】:CSS / HTML: How to center div horizontally?CSS / HTML:如何使 div 水平居中?
【发布时间】:2023-01-23 00:51:03
【问题描述】:

我知道这个问题已被问过数百次,但出于某种原因我无法让它发挥作用。 我的 HTML 和 CSS 都相当简单,但我似乎无法将 div (livechat-wrapper) 水平居中。

我只希望 div 与 textarea 一样宽,并放置在 textarea 的正上方,但它“卡在”了我视图的左侧。

关于如何做到这一点的任何想法?

<body >
  <div class="livechat-wrapper">

  </div>
  <form>
    <textarea maxlength="400" rows="1"id="input_field" class="input_field" type="text" name="q" placeholder="Write a message..."></textarea>
  </form>

</body>
* {

    box-sizing: border-box;
    font-family: "Nunito", sans-serif;
  }
  
  html, body {
    background: linear-gradient(to bottom right, #FDFCFB, #E2D1C3);
    /*linear-gradient(to bottom right, #FDABDD, #374A5A);*/

    width: 800px;
    height: 600px
  }

form {
    display: flex;
    flex-direction: row;
    justify-content: center;
    position: absolute;
    bottom: 0;
    left: 0; 
    right: 0;
    padding-bottom: 10px;

}
.input_field {
    background: rgba(255, 255, 255, 0.4);
    border-radius: 10px;
    width: 90%;
    border: none;
    padding: 1.2em;
    outline: none;
    font-weight: 400;
    box-shadow: 1px 1px 1px black, -0.5px -0.5px white;
    border: none;
    resize: none; 
    outline: none;
  }

.livechat-wrapper {
    background: rgba(255, 255, 255, 0.4);
    box-shadow: 1px 1px 1px black, -0.5px -0.5px white;
    height: 80%;
    width: 90%;
    border-radius: 10px;
    border: 0.05em solid red;
    display: flex;
    flex-direction: row;
    justify-content: center;

 
}

我尝试在 div 上使用,但没有成功

display: flex;
flex-direction: row;
justify-content: center;

【问题讨论】:

    标签: html css alignment


    【解决方案1】:

    有几种方法可以使用 CSS 将 div 水平居中。这里有一些例子:

    使用margin: auto

    div {
      width: 50%; /* or any other width */
      margin: 0 auto;
    }
    

    此方法的工作原理是将左右边距设置为自动,这会将 div 推到父元素的中心。

    使用弹性盒子:

    div {
      display: flex;
      justify-content: center;
    }
    

    此方法通过使用 justify-content 属性使 div 在父元素中居中来工作

    使用网格:

    div {
      display: grid;
      place-items: center;
    }
    

    此方法的工作原理是使用 place-items 属性将 div 在父元素中居中。

    使用转换:翻译:

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

    【讨论】:

      猜你喜欢
      • 2023-02-02
      • 2015-02-10
      • 2013-08-01
      • 2014-04-08
      • 1970-01-01
      • 2011-03-10
      • 2013-03-30
      相关资源
      最近更新 更多