原文链接https://blog.youkuaiyun.com/Chill_Lyn/article/details/100903408
首先我们定义两个div,一大一小,代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#father {
width: 500px;
height: 500px;
background-color: aqua;
}
#child {
width: 200px;
height: 200px;
background-color: red;
}
</style>
</head>
<body>
<div id="father">
<div id="child"></div>
</div>
</body>
</html>
效果:
红色小div默认是在父级div左上角的,这时候我们想让红色小div贴住父级div的底边,如果添加margin-bottom:0px;属性,可以发现是没用的,如下
#child {
width: 200px;
height: 200px;
background-color: red;
margin-bottom:0px;
}
这是因为margin属性只能推开元素,而不能拉近元素!
所以如果想用margin属性让红色小div贴住父级底边,这是只能用margin-top属性将其推下来,如下:
#child {
width: 200px;
height: 200px;
background-color: red;
margin-top:300px;
}
这时我们发现,红色小div非但没有被推下来,而且父级div的margin-top增加了300px,这就又出现了外边距合并的问题,这是只需要在红色小div中加入float属性即可解决,如下:
#child {
width: 200px;
height: 200px;
background-color: red;
margin-top:300px;
float:left;
}
二 给父元素增加padding或者border来解决
#father {
width: 500px;
height: 500px;
background-color: aqua;
border:2px solid green;
或者
padding:25px;
}
三 我们或者可以通过position属性来实现底部贴边,如下:
#father {
width: 500px;
height: 500px;
background-color: aqua;
position: relative;
}
#child {
width: 200px;
height: 200px;
background-color: red;
position: absolute;
bottom: 0;
}
这里需要小注意一下,子div绝对定位后,父级position属性relative,absolute其实都可以,只要声明定位就可以了,因为position属性有一条要求是
绝对定位的元素的位置相对于最近的已定位祖先元素,如果元素没有已定位的祖先元素,那么它的位置相对于最初的包含块。
之后再子div中指定bottom:0;就可以实现底部贴边了。