1.定位+margin(外边距)
代码如下:
html结构:
<body> <div class="box"> <div class="son"></div> </div> </body>
css样式:
<style> .box{ position: relative; width: 500px; height: 300px; background-color: #ccc; } .son{ position: absolute; /* 向右走父元素宽度的一半 */ left: 50%; /* 向左走子元素自身宽度的一半 */ margin-left: -60px; /* 向下走父元素高度的一半 */ top: 50%; /* 向上走子元素自身高度的一半 */ margin-top: -60px; width: 120px; height: 120px; background-color: red; /* margin: 0 auto; 只能使不脱标的块元素水平居中*/ /* margin: auto auto; */ } </style>
效果图:
2.定位+方位名词
代码如下:
html:
<body> <div class="box"> <div class="son"></div> </div> </body>
css:
<style> .box{ position: relative; width: 500px; height: 300px; background-color: #ccc; } .son{ position: absolute; /* 这个技巧子元素必须设置宽高 */ left: 0; right: 0; top: 0; bottom: 0; margin: auto; width: 120px; height: 120px; background-color: red; } </style>
效果图:
3.定位+位移(2d)
代码如下:
html:
<body> <div class="box"> <div class="son"></div> </div> </body>
css:
<style> .father{ position: relative; width: 400px; height: 400px; background-color: pink; } .father .son{ position: absolute; /* 移动的父元素宽的一半 小盒子左边框居中 */ left: 50%; /* 移动自己宽度的一半 */ /* margin-left: -100px; */ /* 移动的父元素高的一半 小盒子上边框居中 */ top: 50%; /* margin-top: -100px; */ transform: translate(-50%,-50% ); width: 200px; height: 200px; background-color: yellowgreen; } </style>
效果图:
4.flex布局
代码如下:
html:
<body> <div class="father"> <div class="son"></div> </div> </body>
css:
<style> .father{ width: 400px; height: 400px; background-color: pink; /* 弹性容器 */ display: flex; /* 水平居中 主轴居中 */ justify-content: center; /* 垂直居中 侧轴居中 */ align-items: center; } /* 弹性盒子 */ .father .son{ width: 100px; height: 100px; background-color: skyblue; } </style>
效果图:
总结
flex布局方法更适用于移动端哦!