我试图让所有内容都居中并占据页面的大约 80%。一切似乎都很好,除了我的两个主要 div 在我的横幅和导航栏上延伸了大约 1 像素,即使它们设置为 80%。
这是 CSS:https://pastebin.com/HM7PLqX0
body {
background: url('bg.png');
background-size: cover;
background-repeat: none;
}
.banner {
font-family: 'Raleway', sans-serif;
color: #f2f2f2;
margin-top: 20px;
text-align: center;
background: url('bg.jpg') no-repeat;
background-size: cover;
background-position: center;
line-height: 120px;
font-size: 40px;
text-shadow: 2px 2px 2px black;
width: 80%;
height: 120px;
margin: 0 auto;
}
.about {
background-color: #333;
opacity: 0.8;
display: inline-block;
vertical-align: top;
text-align: center;
width: 60%;
height: 300px;
font-family: 'Raleway', sans-serif;
color: white;
}
.stats {
background-color: #333;
opacity: 0.8;
display: inline-block;
vertical-align: top;
text-align: center;
width: 20%;
height: 300px;
font-family: 'Raleway', sans-serif;
color: white;
}
.logo {
margin-top: 50px;
font-family: myFirstFont;
color: white;
text-align: center;
font-size: 50px;
}
.topnav {
background-color: #333;
overflow: hidden;
width: 80%;
margin: 0 auto;
}
<div class='logo'>
The Realm MC
</div>
<div class="topnav" id="myTopnav">
<a href="#home" class='active'><i class="fa fa-home" aria-hidden="true"></i>
Home</a>
<a href="#play"><i class="fa fa-play" aria-hidden="true"></i>
Play</a>
<a href="/forum"><i class="fa fa-comment-o" aria-hidden="true"></i>
Forums</a>
<a href="#donate" style="float: right; margin-right: 30px;"><i class="fa fa-heart-o" aria-hidden="true"></i>
Donate</a>
</div>
<div class='banner'>
There are 7 out of 10 players online!
</div>
<br />
<div id='wrapper' style='text-align:center;'>
<div class='about'>
Lorem ipsum<br /> dolor sit amet
</div>
<div class='stats'>
Lorem ipsum<br /> dolor sit amet
</div>
</div>
最佳答案
您没有为 wrapper div 提及任何内容,因此它被分配了 100% 的可用宽度,并且其中的 div 将相应地占用宽度。
尝试将 about div 的宽度减小到 59%,如下所示,这将使两个 div 位于宽度范围的 80% 内:
.about {
background-color: #333;
opacity: 0.8;
display: inline-block;
vertical-align: top;
text-align: center;
width: 59%;
height: 300px;
font-family: 'Raleway', sans-serif;
color: white;
}
这是 fiddle :https://jsfiddle.net/rp1shr4t/
或者您可以像设置topnav div 一样设置wrapper div 的宽度,然后相应地设置内部div 的宽度。
关于html - 将所有元素居中到一定宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44365675/