我试图垂直居中文本内的子div是全高度,但当我这样做,它在底部有额外的间距。如果没有额外的间距,我该怎么做呢?我想有一个导航和一些垂直居中的文本,但没有额外的间距。
html {
height: 100%;
}
body {
margin: 0;
min-height: 100vh;
}
h1 {
margin: 0;
padding: 0;
}
.landing {
background: url(bg.svg);
height: 100vh;
}
.landing-content {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.landing-content h1 {
color: white;
margin: 0;
}
.app {
background-color: black;
height: 100vh;
color: white;
}
<div class="app">
<div class="logo">
<h1>logo</h1>
</div>
<div class="landing">
<div class="landing-content">
<h1>hi, i'm jordan</h1>
</div>
</div>
</div>
使用height: 100vh
是不合适的,它所做的是识别视图宽度作为其高度,该限制限制了高度,并在底部重新创建一个小裂缝。您可以尝试使用height: 100%
来代替
html {
height: 100%;
}
body {
margin: 0;
min-height: 100vh;
}
h1 {
margin: 0;
padding: 0;
}
.landing {
background: url(bg.svg);
height: 100vh;
}
.landing-content {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.landing-content h1 {
color: white;
margin: 0;
}
.app {
background-color: black;
height: 100%;
color: white;
}
<div class="app">
<div class="logo">
<h1>logo</h1>
</div>
<div class="landing">
<div class="landing-content">
<h1>hi, i'm jordan</h1>
</div>
</div>
</div>
删除着陆类高度,并将着陆内容类高度添加为100%。当你将着陆舱高度增加到100vh时,它将覆盖100vh高度。但是logo类已经覆盖了一些高度。所以它溢出了
.landing {
background: url(bg.svg);
}
.landing-content {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
}
working fiddle - https://jsfiddle.net/alimurrazi/36svho08/1/
由于.app
有默认的display: block
,.logo
占用了它需要的多少空间,然后.landing
在下面,占用了额外的100vh,因此您需要滚动以查看其完整的内容。
这里的解决方案是简单地将overflow-y: hidden
添加到.app
,但这仍然使您的文本偏离中心一点。另一个解决方案是给.app
display: flex
,并使用flexx根据需要分配空间。
html {
height: 100%;
}
body {
margin: 0;
min-height: 100vh;
}
h1 {
margin: 0;
padding: 0;
}
.landing {
background: url(bg.svg);
flex-grow: 1;
}
.landing-content {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
}
.landing-content h1 {
color: white;
margin: 0;
}
.app {
background-color: black;
height: 100vh;
color: white;
display: flex;
flex-direction: column;
}
<div class="app">
<div class="logo">
<h1>logo</h1>
</div>
<div class="landing">
<div class="landing-content">
<h1>hi, i'm jordan</h1>
</div>
</div>
</div>
按如下方式修改。app类。
.app {
background-color: black;
height: auto;
color: white;
}