一、margin设置负值后,会怎样?有何应用?
margin 负值有什么效果?
1. margin-left 负值,元素自身向左移动
2. margin-top 负值,元素自身向上移动
3. margin-right 负值,右边的元素向左移动
4. margin-bottom 负值,下边的元素向上移动
margin 负值的应用
1. 增加宽度
2. 圣杯布局
3. 双飞翼布局
二、圣杯布局
两侧区域宽度固定,中间区域自适应
难点
margin-left:-100%; 100%是父级宽度的100%
margin-right:180px; 其他元素当他宽度少了180px
演示代码
<!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>圣杯布局 掘金-WAIT</title>
<style>
* {
margin: 0;
padding: 0;
}
.box {
padding: 0 180px 0 200px;
background-color: #dedede;
overflow: hidden;
}
.content {
width: 100%;
height: 200px;
background-color: red;
}
.item {
float: left;
}
.left {
width: 200px;
margin-left: -100%;
position: relative;
left: -200px;
background-color: blue;
}
.right {
width: 180px;
margin-right: -180px;
background-color: yellow;
}
</style>
</head>
<body>
<div class="box">
<div class="content item">主体</div>
<div class="left item">left-item</div>
<div class="right item">right-item</div>
</div>
</body>
</html>
三、双飞翼布局
两侧区域宽度固定,中间区域自适应,中间的内容优先加载
演示代码
<!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>双飞翼布局 掘金-WAIT</title>
<style>
* {
margin: 0;
padding: 0;
}
.box {
overflow: hidden;
}
.content {
width: 100%;
background-color: #ccc;
}
.subject {
height: 200px;
background-color: red;
margin: 0 180px 0 200px;
}
.item {
float: left;
}
.left {
width: 200px;
margin-left: -100%;
background-color: blue;
}
.right {
width: 180px;
margin-left: -180px;
background-color: yellow;
}
</style>
</head>
<body>
<div class="box">
<div class="content item">
<div class="subject">
主体
</div>
</div>
<div class="item left">item-left</div>
<div class="item right">item-right</div>
</div>
</body>
</html>
四、如何清除浮动
清除浮动的方法
父级加 overflow:hidden;
父级设置 clearfix
父级也浮动
演示代码
.clearfix:after {
content: "";
display: block;
clear: both;
}
五、常见水平居中方法
1. position + margin 负值的方法 (固定宽高)
2. position + margin:auto (固定宽高)
3. display:table-cell + vertical-align:middle (固定宽高)
4. position + transform (不需要固定宽高)
5. flex (不需要固定宽高)
代码展示
1-3 就不展示了
4
* {
margin: 0;
padding: 0;
}
.content {
width: 400px;
height: 400px;
border: 2px solid black;
position: relative;
}
.box {
width: 200px;
height: 200px;
background-color: red;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
5
.content {
width: 400px;
height: 400px;
border: 2px solid black;
display: flex;
justify-content: center;
align-items: center;
}
<body>
<div class="content">
<div class="box">
</div>
</div>
</body>