一、css實現
1、margin
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
*{
margin: 0;
padding: 0;
}
.div1{
height: 500px;
background: #ff0000;
overflow: hidden;/*解決外邊距合併*/
}
.div2{
width: 200px;
height: 200px;
background: #ffff00;
margin:150px auto;/*設置寬纔有用*/
}
</style>
</head>
<body>
<div class="div1">
<div class="div2"></div>
</div>
</body>
</html>
2、定位+margin/translate(x,y)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
*{
margin: 0;
padding: 0;
}
.div1{
height: 500px;
background: #ff0000;
position: relative;
}
.div2{
width: 200px;
height: 200px;
background: #ffff00;
position: absolute;
left:50%;/**/
top:50%;
/*margin-left:-100px;*/
/*margin-top:-100px;*/
/*知道寬高 配合position:absolute;left:50%;top:50%;使用*/
transform: translateX(-50%) translateY(-50%) ;
/*不知道寬高時 配合position:absolute;left:50%;top:50%;使用*/
}
</style>
</head>
<body>
<div class="div1">
<div class="div2"></div>
</div>
</body>
</html>
二、css3彈性盒模型實現
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
.parent{
width: 500px;
height: 500px;
background: #ff0000;
display: -webkit-flex;/*配合使用*/
/*子元素水平對齊*/
-webkit-justify-content: center;
/*子元素垂直對齊*/
-webkit-align-items: center;
}
.child{
width: 100px;
height: 100px;
background: #0f0;
}
</style>
</head>
<body>
<div class="parent">
<div class="child"></div>
</div>
</body>
</html>