CSS_为什么margin-bottom经常无效,或者无法实现子div底部贴边父div?

本文介绍了如何通过CSS调整使小div紧贴父级div底边,涉及margin-bottom失效、float应用、padding/border使用以及position属性定位的方法,并解释了外边距合并问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文链接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;就可以实现底部贴边了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值