html中盒子上下左右居中方法汇总

在页面开发中,常见的盒子上下左右居中方法

一.已知盒子的宽度和高度,需要在父盒子中上下左右居中

1.

html

<div class="box">
    <div class="child">div>
div>

css

.box{width: 300px;height: 300px;border: 1px solid orange;position: relative;}
        .child{width: 100px;height: 100px;border: 1px solid blue;position:absolute;left: 50%;top: 50%;margin-left: -50px;margin-top: -50px;}

2.

html

<div class="box">
    <div class="child">div>
div>

css

.box{width: 300px;height: 300px;border: 1px solid red;position: relative;}
        .child{width: 100px;height: 100px;border: 1px solid green;position:absolute;left: 0;top: 0;right: 0;bottom: 0;margin: auto;}

二.位置宽度盒子上下左右居中

1.

html

<div class="box">
    <div class="child">我是子盒子div>
div>

css

.box{width: 300px;height: 300px;border: 1px solid red;position: relative;}
        .child{width:auto;border: 1px solid green;position:absolute;left: 50%;top: 50%;transform:translate(-50%,-50%);}

你可能感兴趣的:(css)