水平垂直居中的问题,常常在前端面试中被问到,看似很简单的问题,却能考验面试者css基础的一道题目。
水平垂直居中问题主要分为两大类:
一、固定宽高类:
①absolute+负margin;
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>水平垂直居中</title>
<style>
body{
margin:0;
padding:0;
}
#wrapper{
border: 1px solid black;
width: 300px;
height:300px;
position: relative;
}
#box{
background-color:red;
width: 100px;
height: 100px;
position: absolute;
top:50%;
left:50%;
margin-top:-50px;
margin-left:-50px;
}
</style>
</head>
<body>
<div id="wrapper">
<div id="box">水平垂直居中</div>
</div>
</body>
</html>
②absolute+margin:auto;
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>水平垂直居中</title>
<style>
body{
margin:0;
padding:0;
}
#wrapper{
border: 1px solid black;
width: 300px;
height:300px;
position: relative;
}
#box{
background-color:red;
width: 100px;
height: 100px;
position: absolute;
top:0;
left:0;
right: 0;
bottom: 0;
margin:auto;
}
</style>
</head>
<body>
<div id="wrapper">
<div