CSS
五、CSS盒子模型
5.1 标准盒子模型
组成 : content -> padding -> border -> margin
物品 填充物 包装盒 盒子与盒子之间的间距
content : 内容区域 是由width和height组成的
padding : 内边距(内填充)
只写一个值: 30px (上下左右)
写两个值 : 30px 40px ( 上下、左右 )
写四个值 : 30px 40px 50px 60px(上、右、下、左)
单一样式只能写一个值:
padding-left
padding-right
padding-top
padding-bottom
margin : 外边距(外填充)
只写一个值: 30px (上下左右)
写两个值 : 30px 40px ( 上下、左右 )
写四个值 : 30px 40px 50px 60px(上、右、下、左)
单一样式只能写一个值:
margin-left
margin-right
margin-top
margin-bottom
注:
1. 背景色填充到margin以内的区域 (不包括margin区域)
2. 文字在content区域添加。
3. padding不能为负数,而margin可以为负数。
<style>
#box{
width: 200px;height: 200px;background: red;border:10px blue solid;
padding: 30px;
}
</style>
<body>
<div id="box">这是一个盒子</div>
</body>
<style>
#box{
width: 200px;height: 200px;background: red;border:10px blue solid;
padding-left: 30px;
}
</style>
<body>
<div id="box">这是一个盒子</div>
</body>
<style>
#box{
width: 200px;height: 200px;background: red;border:10px blue solid;
padding: 30px 50px;
margin: 10px;}
#box2{
width: 200px;height: 200px;background: black;color: white;}
</style>
<body>
<div id="box">这是一个盒子</div>
<div id="box2">又是一个盒子</div>
</body>
注:背景图也是可填充到margin以内的区域,但背景图是可以修改填充位置的。
5.2 box-sizing样式
该属性允许你以特定的方式定义匹配某个区域的特定元素。取值有content-box(默认值) | border-box。
box-sizing:
盒尺寸,可以改变盒子模型的展示形态。
默认值: content-box : width、height -> content
border-box : width、height -> content padding border
使用的场景:
1. 不用再去计算一些值
2. 解决一些百分比的问题,px与%比换算问题
<style>
#box{
width: 200px;height: 200px;background: red;border:10px blue solid;
padding: 30px 50px;
box-sizing:border-box;
}
input{
width:100%;padding: 10px;box-sizing: border-box;}
</style>
<body>
<div id="box">这是一个盒子</div>
<input type="text">
</body>
5.3 盒子模型的一些问题
1. margin叠加问题
1. margin叠加问题,出现在上下margin同时存在的时候。会取上下中值较大的作为叠加的值。
解决方法:
1.BFC规范
2.只给一个元素添加间距
<style>
#box1{
width: 200px;height: 200px;background: red;margin-bottom: 30px;}
#box2{
width: 200px;height: 200px;background: blue;margin-top: 30px;}
</style>
<body>
<div id="box1"></div