正如您在图像中看到的那样,具有"内部"类的元素在"外部"div内部居中,为此我使用了此堆栈溢出帖子.我试过让Hello World段落出现在居中的div下面而没有使用margin属性作弊,但没有成功.
.outer {
position: relative;
height: 80%;
width: 100%;
}
.inner {
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
vertical-align: middle;
}Run Code Online (Sandbox Code Playgroud)
<div class="outer">
<div class="inner"></div>
<p>Hello World</p>
</div>Run Code Online (Sandbox Code Playgroud)
如果您将多个元素集中在一起,请将它们放在一个容器中并使该容器居中,如下所示:
html, body {
height: 100%;
}
.outer {
background: blue;
position: relative;
height: 100%;
width: 100%;
}
.center {
position: absolute;
transform: translate(-50%, -50%);
top: 50%;
left: 50%;
/* offset margin by 1/2 height of addtl elements */
margin-top: 23px;
}
.inner {
background: lightblue;
width: 300px;
height: 100px;
}
p {
background: lightgray;
text-align: center;
margin: 16px 0 0;
height: 30px;
/* 30 + 16 = 46 ==> 46 / 2 = 23 (offset) */
}Run Code Online (Sandbox Code Playgroud)
<div class="outer">
<div class="center">
<div class="inner"></div>
<p>Hello World</p>
</div>
</div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
991 次 |
| 最近记录: |