范例1
<!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>
div.box1{
width: 300px;
height: 300px;
background-color: lime;
/* 设置为表格内的元素*/
display: table-cell;
/* 垂直居中 */
vertical-align: middle;
}
div.box2{
width: 100px;
height: 100px;
background-color: peru;
/* 让文本元素水平居中 */
text-align: center;
/* 让块元素居中 */
margin: 0 auto;
}
</style>
</head>
<body>
<div class="box1">
<div class="box2">center</div>
</div>
</body>
</html>
范例二:
<!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>
div.box1{
width: 300px;
height: 300px;
background-color:greenyellow ;
/* 开启相对定位 */
position: relative;
}
div.box2{
width: 100px;
height: 100px;
background-color: khaki;
/* 开启绝对定位 绝对定位参照包含块
包含块为开启定位最近的祖先元素*/
position: absolute;
right: 0;
top:0;
left: 0;
bottom: 0;
margin: auto;
}
</style>
</head>
<body>
<div class="box1">
<div class="box2"></div>
</div>
</body>
</html>