我在一个元素中,我需要将 div 中的所有图像放置在同一个位置以制作动画,我将图像绝对放置在彼此之上,尽管这会中断其余部分缩放页面时的代码。
- 示例开始 -
HTML
<div class="a b">
<div class="c d">
<div class="e">
<img class="f" src="" alt="image"/>
</div>
</div>
<div class="c d">
Some content
</div>
</div>
CSS
.a {
clear: both;
padding: 0px;
margin: 0px;
width: 100%; }
.b:before,
.b:after {content:""; display: table; }
.b:after {clear:both; }
.c {
display: block;
float: left;
margin: 1% 0 1% 0%;
}
.d {
margin: 0;
padding: 0;
width: 50%;
}
.e {
position: relative;
margin: 100px auto;
width: 100%;
max-width: 640px;
height: auto;
max-height: 640px;
vertical-align: center;
}
.f {
position: absolute;
margin: 0;
padding: 0;
}
- 示例结束 -
如前所述,这在全屏上效果很好,但在调整大小时,第二个 class="c d"似乎与第一个 class="c d"重叠,我希望它们堆叠在彼此下面,而不是像我创建 class="之前所做的那样f", 有没有办法用纯 css 做到这一点?
最佳答案
要使子项在父项中成为绝对项,您需要使用位置相对的 div 包裹子项。
对于位置设置为 relative 或 absolute 的元素,没有直接的方法来防止它们过度分层,您可以通过计算 left 和 top 值来防止它们。
解决方法是使用阻塞 div。这样做用普通 div 包装你的绝对定位元素并将其高度设置为适合你需要的值检查这个 plunker。
注意带有 .absolute-parent 类的 div 还要注意带有 .blocking-div 类的 div 检查这个 plunker https://plnkr.co/edit/dT1cC8YAY1ENYfhRvncs?p=preview
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<h1>Absolute Positioning</h1>
<div class="absolute-to-page">
to page
</div>
<div class="my-cont">
<div class="blocking-div">
<div class="absolute-parent">
<div class="absolute-to-parent">
to parent
</div>
<div class="absolute-to-parent obj-2">
object two
</div>
</div>
</div>
<div class="absolute-parent">
<p>Some other content</p>
</div>
<div>
<p>Some other content 2</p>
</div>
</div>
</body>
</html>
和CSS代码
/* Styles go here */
.my-cont{
border:1px solid blue;
min-height:400px;
margin-top:200px;
}
.absolute-to-page{
position:absolute;
width:40px;
height:40px;
background:green;
top:0;
}
.absolute-parent{
position:relative;
}
.absolute-to-parent{
position:absolute;
width:40px;
height:40px;
background:red;
top:0;
}
.obj-2{
left:50px;
}
.blocking-div{
height:40px;
}
关于html - 使 child 在父级内绝对化,但不在页面 CSS 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37788446/