CSS / HTML:如何使div水平居中?[duplicate]

xdnvmnnf  于 2023-01-28  发布在  其他
关注(0)|答案(3)|浏览(167)
    • 此问题在此处已有答案**:

(133个答案)
4天前关闭。
我知道这个问题已经被问过几百次了,但是由于某些原因我不能让它工作。我的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;

 
}

我试着在潜水艇上用,但没有运气

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

w6mmgewl1#

有几种方法可以使用CSS使div水平居中。下面是几个例子:

使用margin: auto

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

此方法的工作原理是将左边距和右边距设置为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%);
}
wfveoks0

wfveoks02#

主体的宽度为800px,但是由于绝对定位,这并不影响表单。因此,您需要删除主体上的宽度。同时,div的宽度限制为90%。因此,您可以将其更改为100%并添加box-sizing: border-box;以校正边距,或者添加margin: auto;以使其在页面上居中。

2vuwiymt

2vuwiymt3#

尝试将其添加到CSS中

body {
    display: flex;
    justify-content: center;
    width: 800px;
}

.livechat-wrapper {
    margin: auto;
    width: 90%;
}

相关问题