margin-top的影响
举个栗子:父级整体高度为400px,子元素second为高度的一半,想要去将子元素放到下一半,使用margin-top:50% 发现不是在下一半而是距离底部有一定的距离,常规思想来想50%不就是一半嘛,不应该站一半的高度?
<body>
<div class="first">
<div class="second">
</div>
</div>
</body>
<style>
.first{
width: 300px;
height: 400px;
border: 2px solid red;
}
.second{
width: 100%;
height: 50%;
background-color: aqua;
margin-top:50%
}
</style>
结果却不是想要的结果,那么查阅资料得知呢,margin-top 是基于父级元素的宽度来计算的,那我们将 margin-top:66.666%; 改过来发现,
那么当然还有其他解决办法:
1.可以使用定位布局来
<style>
.first{
width: 300px;
height: 400px;
border: 2px solid red;
position: relative;
}
.second{
width: 100%;
height: 50%;
background-color: aqua;
position: absolute;
top: 50%;
}
</style>
同样可以实现相同的效果
2.就是占父级元素宽度百分比的一半
3.父级overflow:hidden