不定宽高的div盒子和不定宽高的盒子水平垂直居中

让一个不定宽高的div,垂直水平居中的几种实现方式

不定宽高的div垂直居中的方式:

1、使用CSS方法:

父盒子设置:display:table-cell;text-align:center;vertical-align:middle;
不定宽高的div设置:display:inline-block;vertical-align:middle;
代码实现:
html部分
    
我是小猪猪猪
css部分
        *{
            margin: 50px auto;
        }
        .father{
            width: 300px;
            height: 300px;
            background-color: greenyellow;
            display: table-cell;
            vertical-align: middle;
        }
        .son{
            background-color: pink;
        }
运行得页面
不定宽高的div盒子和不定宽高的盒子水平垂直居中_第1张图片
01.png

2、使用CSS3transform

父盒子设置:display:relative
div:transform:transform(-50%,-50%);position:absolute; top:50%;left:50%;
代码实现:
html部分
    
我是小猪猪猪
css部分
    .father{
        width: 200px;
        height: 200px;
        background-color: greenyellow;
        margin: 50px auto;
        position: relative;
    }
    .son{
        background-color: blueviolet;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%) 
    }

运行得页面
不定宽高的div盒子和不定宽高的盒子水平垂直居中_第2张图片
02.png

3、弹性盒子

父盒子设置:display:flex; justify-content:center;align-items:center;
代码实现:
html部分
    
我是小猪猪猪
css部分
    .father{
        width: 200px;
        height: 200px;
        background-color: seagreen;
        margin: 50px auto;
        display: flex;
        justify-content: center;
        align-items: center;
    }
    .son{
        background-color: blueviolet;
    }
运行得页面
不定宽高的div盒子和不定宽高的盒子水平垂直居中_第3张图片
03.png

让一个定宽高的div,垂直水平居中的实现方式

用绝对定位来让一个定宽高的盒子来实现水平垂直居中

1、margin负值

父盒子设置:position:relative;

子盒子:position: absolute;top:50%;left:50%;margin-top:-25px;margin-left:-25px;

不定宽高的div盒子和不定宽高的盒子水平垂直居中_第4张图片
04.png

2.定位的另一种方式

父盒子设置:position:relative;

子盒子:position: absolute;margin:0 auto;top:0;left:0;right:0;bottom:0;

不定宽高的div盒子和不定宽高的盒子水平垂直居中_第5张图片
05.png

你可能感兴趣的:(不定宽高的div盒子和不定宽高的盒子水平垂直居中)