我正在制作一个 Star Wars 粉丝网站并且我有这个设置。我需要使“legends-title”和“canon-title”在较大的 div 中水平居中,并使它们之间的空间随浏览器调整大小。 (本质上,它应该就像我创建了一个 2 列的表格并将列水平居中,并且当浏览器调整大小时,它们之间的间隙应该调整大小以直接保持在 div 左/右半部分的中心)。
HTML:
<div id="starwars-header">
<div id="legends-title">LEGENDS</div>
<div id="canon-title">CANON</div>
</div>
CSS:
#starwars-header {
background: rgb(54, 75, 95); /* Fall-back for browsers that don't support rgba */
background: rgba(54,75, 95, .9);
border: 5px solid black; /*width-style-color*/
text-align: center;
}
#legends-title{
display: inline-block;
color: white;
background-color: green;
}
#canon-title {
display: inline-block;
color: white;
background-color: red;
}
最佳答案
使用 flexbox
- updated fiddle
#starwars-header {
background: rgb(54, 75, 95); /* Fall-back for browsers that don't support rgba */
background: rgba(54,75, 95, .9);
border: 5px solid black; /*width-style-color*/
text-align: center;
display: flex;
justify-content: space-around;
}
#legends-title{
display: inline-block;
color: white;
background-color: green;
}
#canon-title {
display: inline-block;
color: white;
background-color: red;
/*padding-left: 10%; This increases*/
}
<div id="starwars-header">
<div id="legends-title">LEGENDS</div>
<div id="canon-title">CANON</div>
</div>
第二个选项,flexbox
与 #starwars-header
上的伪元素相结合 - updated fiddle
#starwars-header {
background: rgb(54, 75, 95); /* Fall-back for browsers that don't support rgba */
background: rgba(54,75, 95, .9);
border: 5px solid black; /*width-style-color*/
text-align: center;
display: flex;
justify-content: space-around;
}
#starwars-header::before,
#starwars-header::after {
content: '';
}
#legends-title{
display: inline-block;
color: white;
background-color: green;
}
#canon-title {
display: inline-block;
color: white;
background-color: red;
/*padding-left: 10%; This increases*/
}
<div id="starwars-header">
<div id="legends-title">LEGENDS</div>
<div id="canon-title">CANON</div>
</div>
关于html - 将两个 DIV 水平居中,并使它们之间的距离与浏览器宽度成比例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42740638/