已知宽高的div左右居中
<!DOCTYPE html>
<html>
<head>
<title>div水平居中</title>
<style type="text/css">
.myDiv{
width: 300px;
height: 300px;
margin: auto;
background: grey;
}
</style>
</head>
<body>
<div class="myDiv">
this is my div!
</div>
</body>
</html>
未知宽高的div上下左右居中
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>title</title>
<style>
*{
margin: 0;
padding: 0;
}
body,html{
height: 100%;
}
body{
text-align: center;
}
span{
display: inline-block;
height: 100%;
vertical-align: middle;
}
div{
width: 400px;
border: solid 1px red;
vertical-align: middle;
display: inline-block;
*display: inline;
*zoom:1;
text-align: left;
}
</style>
</head>
<body>
<span></span><div class="box">测试文字<br>asdfasdf<br>asdafasdfsdafadsf</div>
</body>
</html>
利用flex布局实现上下左右居中
<!DOCTYPE html>
<html>
<head>
<title>div包含子div垂直居中对齐</title>
<style type="text/css">
body{
/*width: 500px;*/
height: 300px;
border: 4px solid purple;
display: flex; /*设置flex布局*/
justify-content: center;/*水平居中*/
align-items: center;/*竖直居中*/
}
.inner{
width: 160px;
height: 160px;
font-size: 26px;
border: 1px solid green;
}
</style>
</head>
<body>
<div class="demo">
<div class="inner">
<p>这是一个测试这是一个测试</p>
</div>
</div>
</body>
</html>
已知宽高,实现上下左右居中
<!DOCTYPE html>
<html>
<head>
<title>已知宽高div上下左右居中</title>
<style type="text/css">
.main{
width: 400px;
height: 300px;
position: absolute;
left: 50%;
top: 50%;
margin: -150px 0 0 -200px;
background: green;
}
</style>
</head>
<body>
<div class="main">
this is my div!!!
</div>
</body>
</html>