[英]Why does adding float:left/right to my CSS moves another div to the top?
期望的行为:餐厅的中心图像水平居中, margin-top
像素。
具体问题:当我将float
属性添加到左右图像(箭头和放大镜)时,中心图像一直移动到其容器的顶部。
转载者:这是我的 CodePen 的链接: https ://codepen.io/annabaker/pen/gObmWWx
HTML:
<div class="restaurant-widget">
<div class="left-arrow">
<img src="https://i.imgur.com/8T03wEO.png">
</div>
<div class="search">
<img src="https://i.ibb.co/zQX1b7N/zoom-32.png">
</div>
<div class="restaurant">
<img src="https://i.imgur.com/4FeEerb.jpg">
</div>
<div class="header">
THE WATER CLUB
</div>
</div>
CSS:
.restaurant-widget {
color: #4c4c4c;
box-shadow: 1px 1px 16px rgba(0,0,0,.58);
border-radius:1px;
/* this centers the actual widget itself, provided width is defined */
margin: auto;
width: 500px;
height: 900px;
}
.left-arrow img {
margin-top: 50px;
margin-left: 50px;
float: left;
}
.search img {
margin-top: 50px;
margin-right: 50px;
float: right;
}
.restaurant img {
/* this makesthe restaurant image circular */
border-radius: 50%;
border: 5px solid grey;
box-shadow: 1px 1px 16px rgba(0,0,0,.58);
display: block;
margin-top: 100px;
margin-left: auto;
margin-right: auto;
}
这是由于“折叠边距”(您可以在谷歌上搜索详细信息...): .restaurant img
的顶部边距与.restaurant-widget
的边距“合并”,导致容器外的边距。
为避免这种情况,您可以将padding-top: 1px
添加到容器 ( .restaurant-widget
)
每次使用float
,都会从页面中的正常流中删除该元素并将其放在另一个上下文中。 您可以想象浮动元素真的“浮动”在基本上下文中的元素之上。 由于页面中的所有 HTML 都逐行呈现,因此每个人都在其上下文中创建了元素(基于其display
属性)。
当其他图像没有浮动时,您的中心图像的定位发生的方式与它发生的方式相同,因为其他图像与中心图像处于相同的上下文中,因此中心图像占据该位置。 当您应用float
,您会从其上下文中删除其他图像,因此中央图像现在可以在页面上占据一个新位置。 关于上下文这个主题,我建议您在此处进一步阅读: https : //developer.mozilla.org/en-US/docs/Web/Guide/CSS/Block_formatting_context
有一些方法可以实现你想要的。 CSS Flexbox和CSS Grid可能是最好且更简单的方法。 我使用 CSS Grid 重新编写了您的代码,这是一个 Codepen: https ://codepen.io/alac1984/pen/WNbpYmb
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.