本人在进行页面设计时时不时会因为水平居中问题而卡住,所以根据我自己出现的一些问题,总结了解决以下三种类型居中的方法。
其实水平居中都很好解决,主要是垂直居中很折磨人。
以下代码请看die-父容器和baby-子容器,只显示主要代码
图片居中
看die-父容器和baby-子容器
.die{
width: 400px;
height: 400px;
background-color: aqua;
}
.baby{
/* 水平居中 */
text-align: center;
/* 垂直居中 */
padding: 50px;
}
垂直据中使用的padding,通过计算在图片上填充,从而达到居中的效果。
效果
文本居中
.die{
width: 400px;
height: 400px;
background-color: aqua;
position: relative;
}
.baby{
/* 水平居中 */
text-align: center;
/* 垂直居中 使用line-height:高度,高度等于你在的那个盒子的高度*/
line-height: 400px;
}
效果
div居中
先来看一段有问题的代码
错误代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.die{
width: 400px;
height: 400px;
background-color: aqua;
}
.baby{
width: 200px;
height: 200px;
background-color: black;
/* 实现水平居中 */
margin: 100px auto ;
/* 要让div垂直居中,就要计算上下边距了,垂直居中的上下边距为父容器高度的一半减去子容器高度的一半。(400-200)/2=100 */
}
</style>
</head>
<body>
<div class="die">
<div class="baby">
</div>
</div>
</body>
</html>
错误效果图
分析
因为margin属性只有遇到边界才会"停下来"。边界就是border属性或者padding属性,因为父容器没有边界,所以子容器的外边距是相对父容器的父容器的,也就是body。所以我们想要让子容器相对父元素垂直居中,就要给父元素设置一个padding或者border。
正确代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.die{
width: 400px;
height: 400px;
background-color: aqua;
border: 1px solid;
}
.baby{
width: 200px;
height: 200px;
background-color: black;
/* 实现水平居中 */
margin: 100px auto ;
/* 要让div垂直居中,就要计算上下边距了,垂直居中的上下边距为父容器高度的一半减去子容器高度的一半。(400-200)/2=100 */
}
</style>
</head>
<body>
<div class="die">
<div class="baby">
</div>
</div>
</body>
</html>
我们给父容器加上一个border: 1px solid;设置一个边界。