<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>前端面试题</title>
<style type="text/css">
.box1{
width: 400px;
height: 300px;
margin: 0 auto;/* 盒子水平居中 */
text-align: center;/*文字水平居中*/
background-color: green;
}
</style>
</head>
<body>
<!-- 1.css的居中方式 -->
<div class="box1">水平居中</div>
</body>
</html>
1.1水平居中
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>前端面试题</title>
<style type="text/css">
.box2{
width: 400px;
height: 300px;
margin: auto; /* 盒子水平垂直居中 */
position: absolute;/*绝对定位*/
top: 0;
left: 0;
bottom: 0;
right: 0;
text-align: center;/*文字水平居中*/
line-height: 300px;/*文字垂直居中(将行高与盒子高度相等)*/
background-color: greenyellow;
}
</style>
</head>
<body>
<!-- 1.css的居中方式 -->
<div class="box2">水平垂直居中</div>
</body>
</html>
1.2水平垂直居中
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>前端面试题</title>
<style type="text/css">
.box3{
width: 400px;
height: 300px;
position: absolute;/*绝对定位*/
top: 50%;
left: 50%;
/* margin: -150px 0 0 -200px;*/ /* 盒子水平垂直居中 将盒子的中心点移到屏幕的中心点*/
transform: translate(-50%,-50%);/*效果同上*/
text-align: center;/*文字水平居中*/
line-height: 300px;/*文字垂直居中(将行高与盒子高度相等)*/
background-color: blue;
}
</style>
</head>
<body>
<!-- 1.css的居中方式 -->
<!-- <div class="box1">水平居中</div> -->
<!-- <div class="box2">水平垂直居中</div> -->
<div class="box3">水平垂直居中</div>
</body>
</html>
1.3水平垂直居中