CSS——水平垂直居中布局

1. 定宽高

适用于块级元素

1.1 父相子绝 + left top: 父元素宽高/2 + margin: -width/2

父相子绝表示子元素相对父元素移动
left top的百分比是相对于父级元素的宽 高
left top父元素宽高一半表示相对父元素向右向下移动父元素的一半,此时相对移动的点是子元素左上角的点
负外边距表示把子元素中心点移到子元素左上角点的位置(即父元素中心点)

        .father{
            height: 400px;
            width: 400px;
            background-color: beige;

            position: relative;
        }

        .son{         
            height: 200px;
            width: 200px;
            background-color:yellow;

            position: absolute;           
            left: 50%;    
            top: 50%;           
            margin: -100px 0 0 -100px;
        }

1.2 父相子绝 + top bottom right left:0 (上下、左右各相等) + margin:auto

        .father{
            height: 400px;
            width: 400px;
            background-color: beige;

            position: relative;
        }
        .son{
            height: 200px;
            width: 200px;
            background-color:yellow;

            position: absolute;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            margin: auto;
        }

2 不定宽高(都是CSS3)

2.1 设置transform属性的translate值

transform属性允许将元素旋转,缩放,移动,倾斜
translate(x,y)的百分比是相对于元素自身的,这种方法对应于定宽高的第一种方法

        .father{
            height: 400px;
            width: 400px;
            background-color: beige;

            position: relative;
        }
        .son{
            height: 200px;
            width: 200px;
            background-color:yellow;

            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%,-50%);
        } 

2.2 设置父元素flex(弹性)布局

align-items纵轴的对齐方式
justify-content横轴的对齐方式

         .father{
            height: 400px;
            width: 400px;
            background-color: beige;

            display: flex;
            justify-content: center;
            align-items: center;
        }
        .son{
            height: 200px;
            width: 200px;
            background-color:yellow;
        } 

2.3 设置父元素grid(网格)布局

align-self是子元素一个单元格内纵轴上的对齐方式
justify-self是子元素一个单元格内横轴上的对齐方式

        .father{
            height: 400px;
            width: 400px;
            background-color: beige;
            display: grid;
        }
        .son{
            height: 200px;
            width: 200px;
            background-color:yellow;

            justify-self: center;
            align-self: center;
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值