html - 将两个 DIV 水平居中,并使它们之间的距离与浏览器宽度成比例

标签 html css

我正在制作一个 Star Wars 粉丝网站并且我有这个设置。我需要使“legends-title”和“canon-title”在较大的 div 中水平居中,并使它们之间的空间随浏览器调整大小。 (本质上,它应该就像我创建了一个 2 列的表格并将列水平居中,并且当浏览器调整大小时,它们之间的间隙应该调整大小以直接保持在 div 左/右半部分的中心)。

DEMO

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/

相关文章:

javascript - 在 onload 函数中设置 Canvas 背景不起作用

html - 消除 BootStrap 中的移动断点

html - 如何在调整 div 大小时停止摇晃的背景图像

javascript - 单页响应式下拉菜单 - 在 "a"单击时隐藏下拉菜单

html - css-grid div 在 react 组件中使用时不调整大小

css - 如果文本溢出 HTML/CSS,强制 div 滚动?

html - chrome 和 internet explorer 浏览器的下拉列表中不显示县旗

javascript - 在数据刷新时为 flexbox 列设置动画

c# - 根据移动或桌面 HTML 和 CSS 更改图像

html - (Materialize CSS Framework) 'required' 属性在 materialize select 标签中不起作用