在flexbox中保持一个元素在两个不同宽度的元素之间居中 [英] Keep one element centered between two elements of different widths in flexbox
问题描述
我正在制作一个音乐播放控制器,容器有 3 个部分:左、中和右.但是,由于左侧和右侧的宽度不同,中心部分不在 div 的真正中心,但我需要它.我正在使用 flexbox 的 space-between
选项来布局项目.
#container {显示:弹性;对齐内容:间隔;背景颜色:浅灰色;}#容器>div {高度:100px;边框:2px 红色虚线;/*这只是为了外观*/文本对齐:居中;填充:5px;}
<div>左侧</div><div>我想要这个居中</div><div>右侧(用于额外长度的额外文本)</div>
您可以使用边距来近似居中.但是为了让 flexbox 在各种视口中保持一致的完美居中,你必须稍微修改你的 HTML.
您需要使用 display:inline-flex
声明将 #container
的直接子级变成 flex 容器,并给它们一个 flex
1
和 justify-content: center
的值.
从那里,您将您的内容添加到子 div 中.要在左右 div 上对齐,请分别使用 margin-right: auto
和 margin-left: auto
.
#container {显示:弹性;背景颜色:浅灰色;}.柔性 {弹性:1;显示:inline-flex;对齐内容:居中;}.flex >div {高度:100px;边框:2px 红色虚线;文本对齐:居中;填充:5px;}.left div {右边距:自动;}.right div {左边距:自动;}
<div class="left flex"><div>左侧</div><div class="center flex"><div>我想要这个居中</div>
<div class="right flex"><div>右侧(用于额外长度的额外文本)</div>
I am making a music playback controller, and the container has 3 sections: left, center, and right. 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. I am using flexbox's space-between
option to layout the items.
#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.
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
.
From there, you add your content into child divs. To get alignment on the left and right divs, use margin-right: auto
and margin-left: auto
, respectively.
#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>
这篇关于在flexbox中保持一个元素在两个不同宽度的元素之间居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!