我在自己的网站上工作,我对HTML很新。现在我得到了以下代码:
html,
body {
width: 100%;
height: 100%;
margin: 0;
}
h1{
position:absolute;
top:10%;
left:50%;
text-align:center;
}
.block1,
.block2,
.block3,
.block4,
.block5 {
width: 100%;
height: 100%;
}
.block1 {
background: deeppink;
}
.block2 {
background: Crimson;
}
.block3 {
background: LightSeaGreen;
}
.block4 {
background: aqua;
}
.block5 {
background: lightsalmon;
height: 50%;
}

<body>
<section class="block1">
<h1>
Sample Text
</h1>
</section>
<section class="block2">
</section>
<section class="block3">
</section>
<section class="block4">
</section>
<section class="block5">
</section>
</body>
&#13;
现在我的问题:是否可以使用例如block3
等width: 100%
和height: 100%
等维度。因此,我可以像处理第一个正确使用宽度和高度的部分一样对待每个部分。
我想对于较低的部分可以使用300%
,但这看起来很脏。
答案 0 :(得分:1)
问题是你在<h1>
元素上使用绝对定位,并且还试图将文本集中在那里。您需要将text-align: center
应用于父元素,并使用 relative 定位以集中文本。
话虽如此,为了将文本两者纵向和横向集中,最简单的方法是使用 flexbox 。您需要做的就是在display: flex
上设置section
,并在文本元素上设置margin: auto
:
html,
body {
width: 100%;
height: 100%;
margin: 0;
}
section {
width: 100%;
height: 100%;
display: flex;
}
h1 {
margin: auto;
}
.block1 {
background: deeppink;
}
.block2 {
background: Crimson;
}
.block3 {
background: LightSeaGreen;
}
.block4 {
background: aqua;
}
.block5 {
background: lightsalmon;
height: 50%;
}
<body>
<section class="block1">
<h1>
Sample Text
</h1>
</section>
<section class="block2">
<h1>
Sample Text 2
</h1>
</section>
<section class="block3">
<h1>
Sample Text 3
</h1>
</section>
<section class="block4">
<h1>
Sample Text 4
</h1>
</section>
<section class="block5">
<h1>
Sample Text 5
</h1>
</section>
</body>
希望这有帮助! :)
答案 1 :(得分:0)
您可以在这里删除额外的HTML和CSS。
height: 100%
设置html, body
。width: 100%
设置无用。height: 100vh
,仅适用于最后的section
和height: 50vh
。h1
,您可以将纯文本居中放在flex-container中,纯文本将被视为匿名的flex-item。
body {
margin: 0;
}
section {
height: 100vh;
/* become a flex-container */
display: flex;
/* center flex-items vertically */
align-items: center;
/* center flex-items horizontally */
justify-content: center;
}
.block1 {
background: deeppink;
}
.block2 {
background: Crimson;
}
.block3 {
background: LightSeaGreen;
}
.block4 {
background: aqua;
}
.block5 {
background: lightsalmon;
height: 50vh;
}
<section class="block1">
<h1>
Sample Text
</h1>
</section>
<section class="block2">
<h1>
Sample Text 2
</h1>
</section>
<section class="block3">
<h1>
Sample Text 3
</h1>
</section>
<section class="block4">
<h1>
Sample Text 4
</h1>
</section>
<section class="block5">
<h1>
Sample Text 5
</h1>
</section>