我想绝对定位一个div,但它没有粘在顶部,而是有一个空格。容器有position:relative,内部块有position:absoluteCSS规则。我尝试使用代码并注意到更改背景位置有一些效果,但我不知道为什么。
<header>
<div class="header-wrapper">
<div class="header-slogan-1 text-center">Base info</div>
<div class="header-info">Info</div>
</div>
</header>
Run Code Online (Sandbox Code Playgroud)
我想要的是顶部有绿色块(参见小提琴)。
这是小提琴
请任何人都可以解释这种行为并回答为什么该块从顶部移动?
它从顶部移动,因为它相对于其.header-wrapper具有上边距的父级。为了得到想要的结果,你必须删除position: relative从其父级中删除,因此它将相对于视口并放置在顶部。
编辑:我意识到,他的边距实际上应用于包装器的子项,导致边距折叠。为了解决这个问题,您需要应用于overflow: auto父元素。通过这样做,您仍然可以position: relative在包装纸上放置一个,因为它不会被孩子按下。看看演示:
/* header block */
header {
height: 536px;
background-color: #ddd;
background-position: center;
background-size: 100% 536px;
background-repeat: no-repeat;
overflow: hidden;
}
header .header-wrapper {
position: relative;
overflow: auto;
z-index: 2;
}
.header-slogan-1 {
font-size: 32px;
font-weight: 700;
font-style: italic;
margin-top: 88px;
}
.header-wrapper .header-info {
position: absolute;
top: 0;
z-index: 3;
background-color: #4caf50;
max-width: 600px;
padding: 25px 25px 25px 75px;
color: #fff;
}
.text-center {
text-align: center;
}Run Code Online (Sandbox Code Playgroud)
<header>
<div class="header-wrapper">
<div class="header-slogan-1 text-center">Base info</div>
<div class="header-info">Info</div>
</div>
</header>Run Code Online (Sandbox Code Playgroud)