我有一个div元素(1200px宽度),包含3个内部divs.
第一个和最后一个具有静态大小(150px和200px).我希望第二个在徽标和按钮之间居中.问题是我不知道如何集中这个div......
.container {
width: 1200px;
height: 100px;
position: absolute;
margin: 0 auto;
background-color: grey;
}
.logo {
width: 150px;
height: 50px;
float: left;
background-color: darkred;
}
.text {
width: auto;
float: left;
}
.buttons {
width: 200px;
height: 70px;
float: right;
background-color: darkgreen;
}Run Code Online (Sandbox Code Playgroud)
<div class="container">
<div class="logo"></div>
<div class="text">SOME CENTERED TEXT HERE</div>
<div class="buttons"></div>
</div>Run Code Online (Sandbox Code Playgroud)
一种方法是display将.text元素设置为inline-block(并删除float: left),然后添加text-align: center到父元素以使其居中.由于其他元素是浮动的,text-align不会影响它们,并且它只会使内联.text元素居中.
.container {
width: 1200px;
height: 100px;
position: absolute;
margin: 0 auto;
background-color: grey;
text-align: center;
}
.logo {
width: 150px;
height: 50px;
float: left;
background-color: darkred;
}
.text {
display: inline-block;
}
.buttons {
width: 200px;
height: 70px;
float: right;
background-color: darkgreen;
}Run Code Online (Sandbox Code Playgroud)
<div class="container">
<div class="logo"></div>
<div class="text">SOME CENTERED TEXT HERE</div>
<div class="buttons"></div>
</div>Run Code Online (Sandbox Code Playgroud)
或者,您也可以添加margin: auto到.text元素,然后display: flex在父元素上设置.在这样做时,.text元素将水平居中,每侧具有相等的空间.这样做,您也不需要浮动元素(因为它们是flexbox项目).
.container {
width: 1200px;
height: 100px;
position: absolute;
margin: 0 auto;
background-color: grey;
display: flex;
}
.logo {
width: 150px;
height: 50px;
background-color: darkred;
}
.text {
margin: auto;
}
.buttons {
width: 200px;
height: 70px;
background-color: darkgreen;
}Run Code Online (Sandbox Code Playgroud)
<div class="container">
<div class="logo"></div>
<div class="text">SOME CENTERED TEXT HERE</div>
<div class="buttons"></div>
</div>Run Code Online (Sandbox Code Playgroud)