[英]Keep one element centered between two elements of different widths in flexbox
I am making a music playback controller, and the container has 3 sections: left, center, and right. 我正在制作音乐播放控制器,容器有3个部分:左,中,右。 However, since the left and right sides have different widths, the center section isn't in the true center of the div, but I need it to be. 但是,由于左侧和右侧的宽度不同,中心部分不在div的真正中心,但我需要它。 I am using flexbox's space-between
option to layout the items. 我正在使用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>
You can use margins to approximate centering. 您可以使用边距来近似居中。 But in order to get perfect centering with flexbox that's consistent across a variety of viewports, you'll have to slightly modify your HTML somewhat. 但是为了在各种视口中保持一致的flexbox完美居中,你必须稍微修改一下你的HTML。
You need to turn the direct children of #container
into flex containers themselves with a display:inline-flex
declaration and give them a flex
value of 1
and justify-content: center
. 您需要使用display:inline-flex
声明将#container
的直接子项转换为Flex容器,并为它们赋予flex
值1
和justify-content: center
。
From there, you add your content into child divs. 从那里,您将内容添加到子div中。 To get alignment on the left and right divs, use margin-right: auto
and margin-left: auto
, respectively. 要在左右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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.