1.常用写法总结
常用属性 | 说明 |
---|---|
margin | 设置外边距 |
padding | 设置内边距,注意:设置内边距会改变原有容器的大小 |
2.代码示例
<!DOCTYPE html>
<html lang="zh-CN">
<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>test1</title>
<style>
div {
width: 600px;
height: 400px;
border-style: solid;
border-width: 1px;
border-color: rgba(235, 231, 15, 0.4);
border-radius: 200px;
/* 常用的一个属性,让容器居中对齐 */
margin: 0 auto;
/* 添加内边距会改变容器原有的大小,保持容器不变需修改器原有大小属性, 将width属性的800px改成600px */
padding-left: 200px;
}
</style>
</head>
<body>
<div>
这是一段测试用的文字
</div>
</body>
</html>
3.常见需求
1.容器水平居中对齐
/*
让容器居中对齐的条件有两个
1.给容器设置宽度,不能是父容器的百分比,需要具体数字
2.左右的外边距设置为auto
*/
width: 100px
margin: 0 auto;
2.行内元素或行内块元素水平居中对齐
/*
在其父元素上添加该属性即可
*/
text-align: center;
3.外边距合并
参考:外边距合并文档
外边距合并指的是,当两个垂直外边距相遇时,它们将形成一个外边距。合并后的外边距的高度等于两个发生合并的外边距的高度中的较大者
注意:只有标准流中块级元素的垂直外边距才会发生外边距合并。行内元素、浮动或绝对定位之间的外边距不会合并
a.两个元素上下摆放情况
<!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>
.test1 {
width: 100px;
height: 100px;
background-color: pink;
margin-bottom: 20px;
}
.test2 {
width: 100px;
height: 100px;
background-color: blue;
margin-top: 10px;
}
</style>
</head>
<body>
<!--
此时模拟的是上下摆放:
test1设置了margin-bottom: 20px;
test2设置了margin-top: 10px;
此时上下两个盒子的实际外边距是20px,距离的取值是按照两者中较大的来取的
-->
<div class="test1">test1</div>
<div class="test2">test2</div>
</body>
</html>
b.两个元素是包含的情况
元素塌陷:当盒子b包含在盒子a里面,盒子a没有设置内边距或者边框,b盒子和a盒子的上边框会发生合并(下边框合并发生在b盒子高度和a一样时),此时盒子a和盒子b设置上边距也是会去两者中较大的,两个盒子的上边距不会分开造成元素塌陷。
<!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>
.test1 {
width: 100px;
height: 100px;
background-color: pink;
margin-top: 20px;
}
.test2 {
width: 50px;
height: 50px;
background-color: blue;
margin-top: 30px;
}
</style>
</head>
<body>
<!--
两个盒子包含关系
test1设置: margin-top: 20px;
test2设置: margin-top: 30px;
两个盒子会一同距离上边距30px,取值会取两者中较大的。两盒子上边框还是无法分离
-->
<div class="test1">
<div class="test2">test2</div>
</div>
</body>
</html>
解决方案:
/* 方法1: 定义test1盒子设置上边框(注意会扩大盒子宽度) */
border: 1px solid transparent;
/* 方法2: 定义test1盒子设置内边距(注意会扩大盒子宽度) */
padding-top: 1px;
/* 方法3: 在test1盒子上添加下面属性*/
overflow: hidden;