父元素为一个div,子元素是一个块状元素,宽高已知,如何实现子元素在父元素内水平、垂直居中?
1、
//利用相对定位,让子元素垂直居中
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<style type="text/css">
.parent-div {
height: 600px;
width: 600px;
border: 1px solid red;
}
.child-div {
height: 200px;
width: 200px;
border: 1px solid blue;
margin: 0 auto;
position: relative;
top: 50%;
margin-top: -100px;
}
</style>
<body>
<div class="parent-div">
<div class="child-div"></div>
</div>
</body>
</html>
2、//利用Flex(弹性布局)让子元素居中
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<style type="text/css">
.parent-div {
height: 600px;
width: 600px;
border: 1px solid red;
display: flex;
align-items: center;
/* 垂直居中 */
justify-content: center;
/* 水平居中 */
}
.child-div {
background-color: blue;
height: 150px;
width: 150px;
/*margin:0 auto;*/
}
</style>
<body>
<div class="parent-div">
<div class="child-div"></div>
</div>
</body>
</html>
3、利用transform属性实现子元素(宽高未知)水平垂直居中;
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<style type="text/css">
.parent-div {
height: 600px;
width: 600px;
background-color: #ABCDEF;
}
.child-div {
width: 180px;
height: 180px;
background-color: #000;
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
<body>
<div class="parent-div">
<div class="child-div"></div>
</div>
</body>
</html>
以上三种方法是常见的水平垂直居中的。其中Flex是当下使用的比较多的一种布局方式,但是Flex并不是所有浏览器都支持。