我创建了一个与其父级重叠的div,并且div后的边距表现不符合预期。我期望 div后面的内容出现在下标div的之后,但不是。
预期行为:
现实:
这是代码:
HTML :
<div>
<div class="hero">
<div class="heading">
<h1>Greg Potts' Website</h1>
<h4>
Software Developer / Vim-er / Bash-er
</h4>
</div>
</div>
<p>Some content next</p>
</div>
CSS :
.hero {
height: 20vh;
width: 100%;
background: #272c33;
}
.heading {
position: relative;
top: calc(15vh);
width: 50%;
padding: 30px;
margin: auto; /* horizontally center */
background: white;
box-shadow: 3px 3px 3px rgba(0, 0, 0, 0.3);
border-radius: 3px;
}
.heading h1, h2, h3, h4, h5, h6 { text-align: center; }
我怀疑它与clearfix有关,但是尝试了一些解决方案,但未达到预期的效果。
谢谢。
答案 0 :(得分:0)
我将通过重组HTML元素来实现这一点,因为如果使用您设置的结构,那么不添加空白clearfix元素就无法完成。
相反,从.heading
元素中嵌套.hero
并为top
css属性使用负值将是非常简单的。
您还可以将.hero
和.heading
元素包装在容器中,以适应由于top
为负值而剩下的底部边距。
代码如下所示:
HTML
<div>
<div class="hero-container">
<div class="hero"></div>
<div class="heading">
<h1>Greg Potts' Website</h1>
<h4>
Software Developer / Vim-er / Bash-er
</h4>
</div>
</div>
<p>Some content next</p>
</div>
CSS
.hero {
height: 20vh;
width: 100%;
background: #272c33;
}
.heading {
position: relative;
top: calc(-10vh);
width: 50%;
padding: 30px;
margin: auto; /* horizontally center */
background: white;
box-shadow: 3px 3px 3px rgba(0, 0, 0, 0.3);
border-radius: 3px;
}
.hero-container {
margin-bottom: calc(-10vh);
}
.heading h1, h2, h3, h4, h5, h6 { text-align: center; }