如何在父div容器内居中对齐多个子div元素
问题根因
- HTML结构存在嵌套错误:
.configmini是空标签,你需要居中的图片、段落、标题、按钮元素都没有放在这个设置了flex居中的容器内,flex相关的对齐属性自然不会生效。.configmini2的包裹结构是正确的,但外层容器的布局属性存在问题。 - 外层容器
.containerfour设置了display: inline-block,行内块元素默认宽度由内容撑开,margin: auto的水平居中规则仅对设置了明确宽度的块级元素生效,对行内块元素不会生效。 - 部分内部元素设置了固定宽度(比如
.configoneH设置了width: 400px),没有配置水平margin自动对齐,也会导致元素无法居中。
修正方案
你可以按以下代码调整即可实现元素居中:
修正后的CSS代码
/* 修改containerfour为块级元素,设置宽度100%或者你需要的容器宽度 */ .containerfour { display: block; width: 100%; margin: auto; } .configmini, .configmini2{ /* 把flex布局方向改成垂直,让内部元素纵向排列再居中 */ margin: auto; display: flex; flex-direction: column; justify-content: center; align-items: center; width: 100%; } .configone { margin-top: 100px; font-weight: 900; font: bold 55px/58px Nunito Sans; letter-spacing: 0px; color: #404041; text-transform: uppercase; opacity: 1; } .configoneS { /* 去掉多余的固定高度避免文字溢出,保留宽度,加margin: 0 auto居中 */ width: 100px; color: #ff6f3d; text-shadow: 0px 0px 20px #fbf9f4; text-align: center; font: normal normal bold 16px/73px Nunito Sans; letter-spacing: 0px; opacity: 1; margin: 0 auto; } .configoneH { margin-top: 20px; width: 400px; /* 去掉固定高度避免文字溢出 */ color: #404041; text-align: center; font: normal normal normal 35px/40px Nunito Sans Black; letter-spacing: 0px; text-transform: uppercase; /* 固定宽度元素加margin auto水平居中 */ margin: 20px auto 0; } .buttonconfo { margin-top: 5px; text-align: center; font: normal normal normal 10px/30px Nunito Sans Black; letter-spacing: 0px; color: #ffffff; text-transform: uppercase; opacity: 1; background: #ff6f3d 0% 0% no-repeat padding-box; border-radius: 7px; opacity: 1; /* 按钮加margin auto居中 */ display: block; margin: 5px auto 0; } .buttonconfo:hover { cursor: pointer; color: #404042; }
修正后的HTML代码
<div class="containerfour"> <div class="configmini"> <img class="configone" src="img/config_1.svg"> <p class="configoneS">Sustainability</p> <h2 class="configoneH">How much can your country save with refour?</h2> <button class="buttonconfo">Read more</button> </div> <div class="image"> <div class="configmini2"> <img class="configone" src="img/config_2.svg"> <p class="configoneS">Material</p> <h2 class="configoneH">How much can your country save with refour?</h2> <button class="buttonconfo">Read more</button> </div> </div> </div>
内容的提问来源于stack exchange,提问作者OZIM TIM
相关产品推荐
相关产品推荐

