方法一: 已知这个元素的宽高
.div1 {
background-color: blue;
width: 100px;
height: 100px;
/* <!--把元素变成定位元素--> */
position: absolute;
/* <!--设置元素的定位位置,距离上、左都为50%--> */
left: 50%;
top: 50%;
/* <!--设置元素的左外边距、上外边距为宽高的负1/2--> */
margin-left: -50px;
margin-top: -50px;
}
方法二: 使用transform
.div1 {
background-color: blue;
width: 100px;
height: 100px;
/* <!--把元素变成定位元素--> */
position: absolute;
/* <!--设置元素的定位位置,距离上、左都为50%--> */
left: 50%;
top: 50%;
/* <!--设置元素的相对于自身的偏移度为负50%(也就是元素自身尺寸的一半)--> */
transform:translate(-50%,-50%);
}
缺点: 兼容性不好, 只能支持IE9+的浏览器
方法三: margin:auto
父元素设置 position: relative;
子元素:
.div1 {
background-color: blue;
width: 100px;
height: 100px;
/* <!--把元素变成定位元素--> */
position: absolute;
/* <!--设置元素的定位位置,距离上、下左右为0--> */
left: 0;
right: 0;
top: 0;
bottom: 0;
/* <!--设置元素的相对于自身的偏移度为负50%(也就是元素自身尺寸的一半)--> */
margin: auto;
}
缺点: 不支持IE7一下的浏览器
方法四: 弹性布局flex
给父元素添加:
.div0 {
border: 1px solid #000;
width: 300px;
height: 230px;
/* position: relative; */
display: flex;
justify-content: center;
align-items: center;
}