版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/running8/article/details/81504588
仅水平居中比较简单:margin:0 auto; 或者:margin:100px auto;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<style>
body{
padding: 0;
margin: 0;
}
/*水平居中*/
#test{
width: 300px;
height: 200px;
border: 1px solid blue;
background: #78341a;
margin:0 auto;
}
</style>
<body>
<div id="test"></div>
</body>
</html>
垂直居中
1、如果元素有固定宽高:
#test{
width: 300px;
height: 200px;
border: 1px solid blue;
background: #78341a;
/*水平居中
margin:100px auto;
*/
/*如果元素有固定的宽高*/
position: absolute;
/*或者
position: fixed;
*/
top: 0;
left: 0;
right: 0;
bottom: 0;
margin:auto;
}
2、仍然是在元素有固定宽高的情况下:
#test{
width: 300px;
height: 200px;
border: 1px solid blue;
background: #78341a;
/*如果元素有固定的宽高*/
position: fixed;
/*或者
position: absolute;
*/
top: 50%;
left:50%;
margin-left:-150px;
margin-top:-100px;
}
3、在不确定元素宽高的情况下适用:transform: translate(-50%,-50%);
#test{
border: 1px solid blue;
background: #ccc;
/*如果元素有固定的宽高*/
position: fixed;
/*或者
position: absolute;
*/
top: 50%;
left:50%;
transform: translate(-50%,-50%);
}