盒模型是网页中的重要模块,有内容,内外边距,和边框组成。基本模型如下代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>盒子模型</title>
<style type="text/css">
.item1 {width: 200px;
height: 200px;
border:5px solid red;
background: lightgreen;
padding: 5px;
margin: 10px auto;
box-shadow: 12px 12px 20px #ccc;
}
.box1 {width: 200px;
height: 200px;
text-align: center;
line-height: 200px;
background:lightblue;
}
.box2 {width: 200px;
height: 200px;
text-align: center;
background:#854caf;
display: table-cell;
vertical-align: middle;
}
.box3 {width: 200px;
height: 200px;
background:#607d8b;
display: table-cell;
vertical-align: middle;
}
.box4 {width: 200px;
height: 200px;
background:#ffeb3b;
display: table-cell;
vertical-align: middle;
text-align: center;
}
.box4 ul li{display: inline}
.box4 ul{margin: 0;padding: 0}
.cross{width:600px;
height:600px;
background:wheat;
position:relative;
}
.cross1 {width: 200px;
height: 200px;
background: red;
position: absolute;
left: 200px;
}
.cross2 {width: 200px;
height: 200px;
background:blue;
position: absolute;
left: 400px;
top:200px;
}
.cross3 {width: 200px;
height: 200px;
background:green;
position:absolute;
top: 200px
}
.cross4 {width: 200px;
height: 200px;
background: yellow;
top:400px;
left: 200px;
position: absolute;
}
</style>
</head>
<body>
<h3> 盒子内容、边框、内外边距:</h3>
<div class="item1"> 我是盒子的内容
</div>
<hr>
<h3>块内元素是单行元素的居中对齐:</h3>
<div class="box1"> 单行元素在块内的居中对齐
</div>
<hr>
<h3>多行文本在块内元素的居中对齐:</h3>
<div class="box2">
<span> 多行文本的居中对齐</span><br>
<span>实在是不够字数了</span>
</div>
<hr>
<h3>子元素是块元素在块元素中的居中对齐:</h3>
<div class="box3">
<div style="width:40px;height:40px;background:#ff5722;margin:auto"></div>
</div>
<hr>
<h3>子元素是不定宽的在块元素中的居中对齐:</h3>
<div class="box4">
<ul >
<li><a href="">1</a></li>
<li><a href="">2</a></li>
<li><a href="">3</a></li>
<li><a href="">4</a></li>
</div>
<h3 style="text-align:center">绝对定位十字架的制作:</h3>
<div class="cross" >
<div class="cross1">
</div>
<div class="cross2">
</div>
<div class="cross3">
</div>
<div class="cross4">
</div>
</div>
</body>
</html>点击 "运行实例" 按钮查看在线实例
总结:内外边距的设置有多种写法,但是方法相同,方法如下:
例子 1
margin:10px 5px 15px 20px;
上外边距是 10px
右外边距是 5px
下外边距是 15px
左外边距是 20px
例子 2
margin:10px 5px 15px;
上外边距是 10px
右外边距和左外边距是 5px
下外边距是 15px
例子 3
margin:10px 5px;
上外边距和下外边距是 10px
右外边距和左外边距是 5px
例子 4
margin:10px;
所有 4 个外边距都是 10px
关于4种对齐的设置:
1.子元素是单行行内元素: 如a, span <br>
a:水平居中: 在父元素应用: text-align: center;
b:垂直居中: 在行内子元素上设置行高与父元素等高: line-height:
2.子元素是多行的内联文本
a:水平居中: 在父元素应用: text-align: center;
b:垂直居中: 在父元素: display:table-cell;
3.子元素是块元素
a: 水平居中: 子元素设置左右外边距自动适应容器margin: auto;
b:垂直居中: 在父元素: display:table-cell;
4. 子元素是不定宽的块元素
a: 水平居中: 子元素转为行内元素,父级加: text-align:center
b: 垂直居中: 在父元素: display:table-cell;
外边距在垂直方向上会发生塌陷,以数值大的为准,向大数值方向走
相对定位一般用在绝对定位的父级。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号