CSS/HTML技术问题:如何水平居中livechat-wrapper div?
问题:无法将livechat-wrapper div水平居中并与textarea对齐
我知道该问题已被多次提及,但始终无法解决。我的HTML与CSS代码较为简单,却无法将livechat-wrapper div水平居中。我希望该div宽度与textarea一致,且位于textarea正上方,但它目前紧贴视图左侧。
我的HTML代码
<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>
我的CSS代码
* { box-sizing: border-box; font-family: "Nunito", sans-serif; } html, body { background: linear-gradient(to bottom right, #FDFCFB, #E2D1C3); 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;
解决思路
1. 调整body布局实现水平居中
给body添加flex布局,让内部元素垂直排列并水平居中,这样livechat-wrapper就能自动和下方textarea对齐:
html, body { background: linear-gradient(to bottom right, #FDFCFB, #E2D1C3); width: 800px; height: 600px; /* 新增以下两行 */ display: flex; flex-direction: column; align-items: center; }
2. 优化livechat-wrapper样式
移除livechat-wrapper中多余的flex属性(你之前加的是让内部元素居中,不是让自身居中),同时添加margin-bottom和下方textarea拉开距离:
.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; /* 移除多余flex属性,新增margin-bottom */ margin-bottom: 10px; }
3. 原理说明
body设置display: flex+flex-direction: column后,内部元素垂直排列;align-items: center让所有子元素水平居中,正好匹配textarea的90%宽度居中效果。- form是绝对定位,位置不受body布局影响,依然固定在底部。
内容的提问来源于stack exchange,提问作者N G
相关产品推荐
相关产品推荐

