批改状态:合格
老师批语:
- 实例演示box-sizing属性;
- 实例演示常用的元素居中方式
box-sizing 属性定义盒子的尺寸,默认值 content-box 只包含内容区,若盒子设置有 padding 和 border 属性,box-sizing 默认值并不包含它们,可以通过设置 box-sizing 属性为 border-box 将盒子尺寸延展到包含 padding 和 border 的属性值,盒子的内容区被挤压。
body 标签中添加一个盒子
<div class="box">content</div>
style 标签添加 css 并设置属性
/* 定义 1em = 10px */:root {font-size: 10px;}/*盒子尺寸 box-sizing 默认是 content-box 内容框宽度 width 10em = 100px高度 height 8em = 80px*/.box {width: 10em;height: 8em;border: 5px solid gray;padding: 15px;margin: 20px;background-color: lightgreen;/* 背景默认延展到 padding 区,裁剪到内容区 */background-clip: content-box;/* 盒子尺寸默认值,内容框 */box-sizing: content-box;}

style 标签中,继续添加 css 设置属性 box-sizing: border-box; 属性
/*设置 box-sizing 属性为 border-box ,盒子尺寸盒子宽 100px 包含 padding 和 border 的值盒子高 80 px 包含 padding 和 border 的值内容框被挤压成内容宽度 = 100px - padding*2 - border*2 = 100 - 15*2 - 5*2 = 60px内容高度 = 80px - padding*2 - border*2 = 80 - 15*2 - 5*2 = 40px*/.box {box-sizing: border-box;}
box-sizing: border-box; 后,盒子尺寸 100x80 包含 padding 和 border 内容被挤压成 60x40px
body 中盒子 box 设置内元素 a 标签
<div class="box"><a href="https://php.cn" title="php">php</a></div>
text-align:center; 行内元素水平居中
/* 行内元素水平居中 */.box {text-align: center;}
body 中盒子 box 设置行内块 img 标签
<!-- 行内块元素水平居中 --><div class="box"><img src="https://www.php.cn/favicon.ico" alt="php" /></div>
text-align:center; 行内块图片水平居中
.box {text-align: center;}
<!-- 块元素水平居中 --><div class="box"><p>content</p></div>
margin: auto; 属性
/* 块元素水平居中 */.box p {margin: auto;width: 5em;height: 4em;background-color: lightsalmon;}
<!-- 行内元素垂直居中 --><div class="box"><a href="https://php.cn" title="php">php</a></div>
line-height 为父级 .box 的高度,即可让行内元素垂直居中,css 设置如下
/* 行内元素垂直居中 */.box {height: 8em;}.box a{line-height: 8em;}
<!-- 块元素垂直居中 --><div class="box"><p>content</p></div>
/* 块元素垂直居中 */.box {/* 去掉父级高度,改为 auto */height: auto;/* 由 padding 挤出高度 */padding: 3em 0;}.box p {width: 5em;height: 3em;background-color: lightskyblue;/* 让 p 标签的内容垂直居中,行高 = p 标签高度 3em */line-height: 3em;}

<!-- 行内元素水平居中且垂直居中 --><div class="box"><a href="https://php.cn" title="php">php</a></div>
text-align: center; 让行内元素 a 水平居中,设置 a 的行高与父级高度相同,实现垂直居中
/* 行内元素水平居中且垂直居中 */.box {width: 10em;height: 8em;padding: 5em;/* 设置子元素 a 标签水平居中 */text-align: center;}.box a {/* 设置行高 8em 与父级高度相同,实现垂直居中 */line-height: 8em;}

<!-- 块元素水平且垂直居中 --><div class="box"><p>content</p></div>
/* 块元素水平且垂直居中 */.box {/* 去掉父级高度,改为 auto */height: auto;/* 由 padding 挤出高度 */padding: 3em 0;box-sizing: border-box;}.box p {margin: 2em;width: 5em;height: 3em;background-color: lightskyblue;/* 让 p 标签的内容垂直居中,行高 = p 标签高度 3em */line-height: 3em;}

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号