前端学习日记之盒子居中方式
方式1
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body,html {
height:100%;
padding: 0;
margin: 0
}
.box {
position: relative;
width: 400px;
height: 400px;
float: left;
background-color: red;
}
.box_1 {
position: absolute;
width: 200px;
height: 200px;
float: left;
background-color: blue;
margin-top: 100px;
margin-left: 100px;
}
</style>
</head>
<body>
<div class="box">
<div class="box_1"></div>
</div>
</body>
</html>
效果
方法2负间距
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.box {
position: relative;
width: 400px;
height: 400px;
float: left;
background-color: red;
}
.box_1 {
position: absolute;
width: 200px;
height: 200px;
float: left;
background-color: blue;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -100px;
}
</style>
</head>
<body>
<div class="box">
<div class="box_1"></div>
</div>
</body>
</html>
效果
方法3
父元素输入 overflow: hidden;在定义子元素上左外边距
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.box {
width: 400px;
height: 400px;
background-color: red;
overflow: hidden;
}
.box_1 {
background-color: yellow;
width: 200px;
height: 200px;
margin-top: 100px;
margin-left: 100px;
}
</style>
</head>
<body>
<div class="box">
<div class="box_1"></div>
</div>
</body>
</html>
效果
方法4
display:table-cell 将父元素盒子转换为表格单元格的形式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.box {
display: table-cell;
width: 400px;
height: 400px;
background-color: red;
}
.box_1 {
background-color: yellow;
width: 200px;
height: 200px;
margin-top:100px;
margin-left: 100px;
}
</style>
</head>
<body>
<div class="box">
<div class="box_1"></div>
</div>
</body>
</html>
效果