我想使用 position:relative
和 left
属性使子 div 重叠。由于重叠,我想减少父宽度。然而事实上,父div并没有减少。
这是我的代码笔。 https://codepen.io/anon/pen/eRMMwW
HTML
<div class="mother">
<div class="child">1</div>
<div class="child">2</div>
<div class="child">3</div>
<div class="child">4</div>
</div>
CSS
div.mother {
background-color: red;
display:inline-block;
}
div.child {
background-color: blue;
width: 50px;
height: 50px;
display: inline-block;
position: relative;
}
div.child:nth-child(2) {
left: -25px;
background-color: yellow;
}
div.child:nth-child(3) {
left: -50px;
background-color: pink;
}
div.child:nth-child(4) {
left: -75px;
background-color: green;
}
如您所见,mother
div 宽度与其子级宽度不匹配,并且存在超红部分。我想删除超出红色的部分。你知道这里有什么解决办法吗?还有一点。我尝试避免 flex
和 float
。
Kumar 的更新,为什么不将子级的宽度减少一半。
我想制作一组相互重叠的图像。假设那些 child
div 是这样的圆形边框。正如您所看到的,将 child 的宽度设置为一半并不是一个好主意。
最佳答案
您可以使用negative margins在内部 div 上 (margin-left: -25px
),同时为父 div 提供偏移边距 - (margin-left: 25px
)
div.mother {
background-color: red;
display: inline-block;
margin-left: 25px;
}
div.child {
background-color: blue;
width: 50px;
height: 50px;
display: inline-block;
position: relative;
margin-left: -25px;
}
div.child:nth-child(2) {
background-color: yellow;
}
div.child:nth-child(3) {
background-color: pink;
}
div.child:nth-child(4) {
background-color: green;
}
<div class="mother">
<div class="child">1</div>
<div class="child">2</div>
<div class="child">3</div>
<div class="child">4</div>
</div>
如果您想删除 :hover
上的重叠,这也很容易制作动画
动画草稿:
div.mother {
background-color: red;
display: inline-block;
margin-left: 25px;
z-index: 1; /* botttom layer */
}
div.child {
background-color: blue;
width: 50px;
height: 50px;
display: inline-block;
position: relative;
margin-left: -25px;
}
div.child:nth-child(2) {
background-color: yellow;
z-index: 2; /* botttom layer +1 */
}
div.child:nth-child(3) {
background-color: pink;
z-index: 3; /* botttom layer +2 */
}
div.child:nth-child(4) {
background-color: green;
z-index: 4; /* botttom layer +3 */
}
div.child:hover {
position: relative;
animation-name: slide;
animation-duration: 1s; /*animation speed */
animation-iteration-count: 1;
animation-fill-mode: forwards; /* makes animation stop at 100% and not revet back to original state */
cursor: pointer;
}
div.child:nth-child(4):hover {
animation-name: none; /* doesn't need animation othewise you would see red background from parent div */
}
@keyframes slide {
0% {
margin-right: 0px;
}
100% {
margin-right: 20px; /* pushes the next div out so you can see current div. */
}
}
<div class="mother">
<div class="child">1</div>
<div class="child">2</div>
<div class="child">3</div>
<div class="child">4</div>
</div>
关于html - CSS,重叠子div但父div的宽度保持不变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44870550/