以下七种方法:
- 父元素设置display:flex 子元素设置:margin:auto
- 父元素设置display:flex; justify-content:center; align-items:center;
- 父元素设置 display:grid;justify-content:center;align-items:center
- 子绝父相;配合属性全部为0,margin:auto
- 子绝父相;top:50%;left:50%;margin-left:-width/2;margin-top:-height/2
-
给父元素设置border或者overflow: hidden;
给子元素设置margin:(父height-子height)/2(父width-子width)/2
-
给父元素设置border-box 设置padding:(父height-子height)/2(父width-子width)/2
执行结果:
该例子的html代码:
<body>
<div class="parent">
<div class="child"></div>
</div>
</body>
第一种:父元素设置display:flex 子元素设置:margin:auto
.parent { width: 300px; height: 300px; background-color: paleturquoise; display: flex; } .child { width: 100px; height: 100px; background-color: palevioletred; margin: auto; }
第二种:父元素设置display:flex; justify-content:center; align-items:center;
.parent { width: 300px; height: 300px; background-color: paleturquoise; display: flex; justify-content: center; align-items: center; }
第三种:父元素设置 display:grid;justify-content:center;align-items:center
.parent { width: 300px; height: 300px; background-color: paleturquoise; display: grid; justify-content: center; align-items: center }
第四种:子绝父相;配合属性全部为0,margin:auto
.parent { width: 300px; height: 300px; background-color: paleturquoise; position: relative; } .child { width: 100px; height: 100px; background-color: palevioletred; position: absolute; margin: auto; top: 0; bottom: 0; left: 0; right: 0; }
第五种:子绝父相;top:50%;left:50%;margin-left:-width/2;margin-top:-height/2
.parent { width: 300px; height: 300px; background-color: paleturquoise; position: relative; } .child { width: 100px; height: 100px; background-color: palevioletred; position: absolute; margin: auto; top: 50%; left: 50%; margin-left: -50px; margin-top: -50px; }
第六种:
给父元素设置border或者overflow: hidden;
给子元素设置margin:(父height-子height)/2(父width-子width)/2
.parent { width: 300px; height: 300px; background-color: paleturquoise; border: 1px solid red; } .child { width: 100px; height: 100px; background-color: palevioletred; margin: 100px 100px; }
第7种:
给父元素设置border-box 设置padding:(父height-子height)/2(父width-子width)/2
.parent { width: 300px; height: 300px; background-color: paleturquoise; box-sizing: border-box; padding: 100px 100px; } .child { width: 100px; height: 100px; background-color: palevioletred; }