我正在尝试模仿以下网站:http://weareundefined.be/一旦你通过点击它通过了第一页,就会有一台电脑和它下面的一小段。
使用 dev webtool 分析网站后,我仍然无法正确居中元素。我尝试了 top: 50%
和 position: relative
,但它没有正确居中。
我试图分解成必要的 CSS,但仍然无法重新创建它。
代码:
<div style={{height: '100%’}}>
<div className="container">
<div id="rotate-container">
<div>
Center Me
</div>
</div>
<h1> We are undefined</h1>
<p>We're a creative agency with a focus on digital.</p>
</div>
</div>
CSS(SCSS):
.container {
height: 100%;
position: relative;
padding: .5em;
margin: 0 auto;
max-width: 400px;
text-align: center;
top: 50%;
}
#rotate-container {
div {
color: #fb3131;
font-size: 40px;
font-weight: bold;
display: block;
}
}
我可能遗漏了什么或做错了什么?他们如何处理元素的大小调整?任何建议或指导将不胜感激。
预先感谢您,一定会接受并点赞回答。
最佳答案
你很接近。 html
和 body
也需要是 height: 100%;
,否则它的子元素不会是 100% 的视口(viewport)。
.container
不需要 height: 100%;
。由于您已经在 top: 50%;
处拥有 .container
,只需使用 transform: translateY(-50%);
将其向上移动它自身宽度的 50%,因此它的中心位于浏览器的中心。
body, html {
height: 100%;
}
.container {
position: relative;
padding: .5em;
margin: 0 auto;
max-width: 400px;
text-align: center;
top: 50%;
transform: translateY(-50%);
}
#rotate-container div {
color: #fb3131;
font-size: 40px;
font-weight: bold;
display: block;
}
<div style="height:100%;">
<div class="container">
<div id="rotate-container">
<div>
Center Me
</div>
</div>
<h1> We are undefined</h1>
<p>We're a creative agency with a focus on digital.</p>
</div>
</div>
您还可以将 flexbox 与 align-items: center;
一起使用
body,
html {
height: 100%;
}
.container {
position: relative;
padding: .5em;
margin: 0 auto;
max-width: 400px;
text-align: center;
}
#rotate-container div {
color: #fb3131;
font-size: 40px;
font-weight: bold;
display: block;
}
<div style="height:100%; display: flex; align-items: center;">
<div class="container">
<div id="rotate-container">
<div>
Center Me
</div>
</div>
<h1> We are undefined</h1>
<p>We're a creative agency with a focus on digital.</p>
</div>
</div>
关于javascript - 如何将元素 <div> 和 <h1> 从上到下居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42214658/