提问人:Gregory Potts 提问时间:3/8/2019 更新时间:3/8/2019 访问量:680
如何向相对 div 溢出的父级添加边距以向下移动内容
How to Add Margin to Relative Div Overflowing Parent to Move Content Down
问:
我创建了一个与其父级重叠的 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赞
Ivica Pesovski
3/8/2019
#1
为了实现这一点,我会重组 HTML 元素,因为如果不添加空白的 clearfix 元素,就无法完成您设置的结构。
相反,从元素中取消嵌套并改用负值作为 css 属性将非常简单。.heading
.hero
top
此外,还可以将 和 元素包装在容器中,以调整由于负值而留下的下边距。.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; }
评论
1赞
Gregory Potts
3/8/2019
像魅力一样工作!谢谢!Благодарам!
评论