css小问题汇总(持续更新)

小div盒子在大div盒子中如何水平垂直居中

关于如何设置小盒子在大盒子里面水平垂直方向同时居中的实现方法有很多种,下面列举了常用的几种。

基础代码样式

html代码

// 大盒子嵌套小盒子 小盒子水平垂直居中
<div class="parent">
    <div class="child"></div>
</div>

css代码

.parent{
	height:600px;
	width:600px;
	background-color:red;
}
.child{
	height:300px;
	width:300px;
	background-color:chocolate;
}

1.使用定位实现
父盒子相对定位,子盒子绝对定位,top为父盒子的50%(将整个子盒子看成一个点),当移动父盒子的50%,相当于多移动子盒子宽度的50%,所以需要margin-top向上移动-50%

.parent{
        height:600px;
        width:600px;
        background-color:red;
        position: relative;
    }
.child{
        height:300px;
        width:300px;
        background-color:chocolate;
        position: absolute;
        top:50%;   // 相当于父盒子高的50%
        left:50%;   //相当于父盒子宽的50%
        margin-top: -150px;   /*这里是小盒子高的一半*/
        margin-left: -150px;   /*这里是小盒子宽的一半*/
		//top:25%;  也可以实现
        //left:25%;
    }

2.使用margin:auto实现

设置margin自动适应,然后设置定位的上下左右都为0,就如四边均衡受力从而实现盒子
的居中;

.parent{
        height:600px;
        width:600px;
        background-color:red;
        position: relative;
    }
.child{
        height:300px;
        width:300px;
        background-color:chocolate;
        position: absolute;
        top:0;
        left:0;
        right: 0;
        bottom: 0;
        margin: auto;
    }

3.使用display:table-cell;

display:table-cell属性指让标签元素以表格单元格的形式呈现,类似于td标签,组合使用vertical-align,text-align,可以使父元素内的所有行内元素水平垂直居中(也就是将内部的元素设置display:inline-block)

.parent{
        height:600px;
        width:600px;
        background-color:red;
        display: table-cell;
        vertical-align: middle;
        text-align: center;
    }
 .child{
        height:300px;
        width:300px;
        background-color:chocolate;
        display: inline-block;
    }

4、弹性盒子实现

只用给父盒子display: flex,不需要给子盒子设置。

.parent{
        height:600px;
        width:600px;
        background-color:red;
        display: flex;
        justify-content: center;
        align-items: center;
    }
 .child{
        height:300px;
        width:300px;
        background-color:chocolate;
    }

实现图片遮住div,显示图片颜色

在这里插入图片描述

react被遮盖住,此时通过设置z-index属性,实现图片遮住div,显示图片颜色

css代码

height: 100px;
   width: 100px;
   margin: 10px 580px;
   position: absolute;
   display: inline-block;
   background-repeat: no-repeat;
   z-index: 3;     

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值