CSS让元素置于容器底部

CSS让元素置于容器底部

回顾

之前 回顾 已经描述了如何让 CSS在不影响总体布局情况下让元素自由缩小
效果如图所示
在这里插入图片描述
此时代码如下

<body>
    <div class="box1">box1box1</div>
    <div class="box_0"> 
        <!--class = "box_0的外层盒子"-->
        <div class="box2">box2box2</div>
    </div>
    <div class="box3">box3box3</div>
    <div class="box4">box4box4</div>
    <div class="box5">box5box5</div>
</body>
<style>
    .box1{
     
     
        height: 100px;
        background-color: red;
    }
    .box_0{
     
     
        height: 100px;
    }
    .box2{
     
     
        height: 50px;
        background-color: blue;
    }
    .box3{
     
     
        height: 100px;
        background-color: green;
    }
    .box4{
     
     
        height: 100px;
        background-color: gray;
    }
    .box5{
     
     
        height: 100px;
        background-color: rgb(233, 30, 206);
    }
</style>

改进

这时box2包含于容器box_0中,若想让box2置于box_0底部而不是顶部实现下图所示效果
在这里插入图片描述
可以把box_0(父元素)的定位设定为相对定位,而box2的定位设定为绝对定位,且其bottom设定为0,即

    .box_0{
        position: relative;
        height: 100px;
    }
    .box2{
        position: absolute;
        height: 50px;
        background-color: blue;
        bottom: 0;
    }

此时已经成功了一半,但是box2设定为绝对定位后,默认就不是100%的宽度了,而是内容多宽就多宽,此时效果如下
在这里插入图片描述

进一步改进

此时可以获取box_0的宽度,然后为box2设定同样的宽度,首先为box_0设置一个id = “box_width”,然后用document.getElementById(“box_width”).offsetWidth获取其宽度

	<div class="box_0" id="box_width"> 
		<!--class = "box_0的外层盒子"-->
        <div class="box2">box2box2</div>
    </div>
    <script>
        window.onload = function(){
     
     
            w = document.getElementById("box_width").offsetWidth
        alert(w);
    }
    </script>

可以得到
在这里插入图片描述
此时,为box2设定宽度

    .box2{
        position: absolute;
        height: 50px;
        width: 1520px;
        background-color: blue;
        bottom: 0;
    }

最后效果为
在这里插入图片描述
最终代码预览

<body>
    <div class="box1">box1box1</div>
    <div class="box_0" id="box_width"> 
		<!--class = "box_0的外层盒子"-->
        <div class="box2">box2box2</div>
    </div>
    <script>
        window.onload = function(){
     
     
            w = document.getElementById("box_width").offsetWidth
        alert(w);
    }
    </script>
    <div class="box3">box3box3</div>
    <div class="box4">box4box4</div>
    <div class="box5">box5box5</div>
</body>
<style>
    .box1{
     
     
        height: 100px;
        background-color: red;
    }
    .box_0{
     
     
        position: relative;
        height: 100px;
    }
    .box2{
     
     
        position: absolute;
        height: 50px;
        width: 1520px;
        background-color: blue;
        bottom: 0;
    }
    .box3{
     
     
        height: 100px;
        background-color: green;
    }
    .box4{
     
     
        height: 100px;
        background-color: gray;
    }
    .box5{
     
     
        height: 100px;
        background-color: rgb(233, 30, 206);
    }
</style>

猜你喜欢

转载自blog.csdn.net/qq_44742090/article/details/108943546