我正在制作音乐播放控制器,容器有3个部分:左,中,右.但是,由于左侧和右侧的宽度不同,中心部分不在div的真正中心,但我需要它.我正在使用flexBox的space-between选项来布局项目.
#container { display: flex; justify-content: space-between; background-color: lightgrey; } #container > div { height: 100px; border: 2px dashed red; /*This is only for looks*/ text-align: center; padding: 5px; }
<div id="container"> <div>Left Side</div> <div>I want this centered</div> <div>Right Side (Extra text for extra length)</div> </div>
解决方法
您可以使用边距来近似居中.但是为了在各种视口中保持一致的flexBox完美居中,你必须稍微修改一下你的HTML.
您需要使用display:inline-flex声明将#container的直接子项转换为flex容器,并为它们赋予flex值1和justify-content:center.
从那里,您将您的内容添加到子div.要在左右div上对齐,请分别使用margin-right:auto和margin-left:auto.
#container { display: flex; background-color: lightgrey; } .flex { flex: 1; display: inline-flex; justify-content: center; } .flex > div { height: 100px; border: 2px dashed red; text-align: center; padding: 5px; } .left div { margin-right: auto; } .right div { margin-left: auto; }
<div id="container"> <div class="left flex"> <div>Left Side</div> </div> <div class="center flex"> <div>I want this centered</div> </div> <div class="right flex"> <div>Right Side (Extra text for extra length)</div> </div> </div>