11. CSS从基础样式到盒模型与形状绘制
在前端开发中,CSS(层叠样式表)是控制网页样式和布局的核心技术。整理了关于 CSS 基础样式、文本样式、盒模型以及形状绘制的一些心得。以下是详细的学习笔记。
一、基础样式设置
1. 字体样式
字体样式是网页视觉呈现的重要组成部分,常用的 CSS 属性包括:
- font-size: 设置字体大小(如 20px)。
- font-weight: 设置字体粗细(如 bold 或数值 100-900)。
- font-family: 设置字体类型(如 “楷体”)。
- font-style: 设置字体样式(如 italic 斜体)。
- font-variant: 设置字母大小写(如 small-caps 小型大写字母)。
- color: 设置字体颜色(如 red 或 rgba(100, 85, 15, 0.877))。
示例代码:
<style>#font {font-weight: bold;font-family: "楷体";font: bold italic 30px "楷体";color: red;}
</style>
<p id="font">示例文本</p>
2. 文本样式
文本样式可以进一步美化文字内容,常用的 CSS 属性包括:
- text-align: 文本对齐方式(如 center 居中)。
- text-indent: 首行缩进(如 2em)。
- text-decoration: 文本修饰(如 underline 下划线)。
- text-shadow: 文本阴影(如 5px 0px 1px gold)。
- text-transform: 文本大小写转换(如 capitalize 首字母大写)。
- word-spacing: 单词间距(如 10px)。
- letter-spacing: 字母间距(如 10px)。
- line-height: 行高(如 50px)。
示例代码:
<style>p {text-align: center;text-indent: 2em;text-decoration: underline;text-shadow: 5px 0px 1px gold;text-transform: capitalize;word-spacing: 10px;letter-spacing: 10px;line-height: 50px;}
</style>
<p>示例文本</p>
二、盒模型
盒模型是 CSS 布局的核心概念,包括内容(content)、内边距(padding)、边框(border)和外边距(margin)。
1. 边框设置
边框样式可以通过 border 属性或单独设置每一边的样式:
- border: 统一设置四边样式(如 10px solid rgb(202, 12, 12))。
- border-top / border-bottom / border-left / border-right: 单独设置每一边的样式。
示例代码:
<style>.box {width: 100px;height: 100px;background-color: gold;border-top: 10px solid rgb(202, 12, 12);border-bottom: 5px dotted black;border-left: 30px double green;border-right: 50px groove blue;}
</style>
<div class="box">盒模型示例</div>
2. 内边距与外边距
内边距和外边距用于控制元素内部和外部的空间:
- padding: 设置内边距(如 50px 40px 30px)。
- margin: 设置外边距(如 100px auto 用于块元素居中)。
示例代码:
<style>.box {width: 100px;height: 100px;background-color: gold;padding: 50px 40px 30px;margin: 100px auto;}
</style>
<div class="box">盒模型示例</div>
3. 外边距合并与穿透
外边距合并是指相邻元素的外边距会合并为一个较大的值。子元素的外边距可能会穿透父元素,导致父元素也位移。
示例代码:
<style>.big {background-color: red;border: 1px solid #000;height: 200px;}.small {background-color: yellow;width: 50px;height: 50px;margin-top: 100px; /* 可能导致父元素位移 */}
</style>
<div class="big"><div class="small"></div>
</div>
三、形状绘制
CSS 可以通过边框和圆角属性绘制简单的几何形状。
1. 圆形与切角
- border-radius: 设置圆角(如 50% 创建圆形)。
- 单独设置某一边的圆角(如 border-top-left-radius)。
示例代码:
<style>.circle {height: 100px;width: 100px;background-color: red;border: 10px solid #000;border-top-left-radius: 50px;border-bottom-right-radius: 50px;}
</style>
<div class="circle"></div>
2. 三角形
通过设置边框的宽度和透明度,可以创建三角形:
示例代码:
<style>.tri {height: 0px;width: 0px;border-top: 100px solid black;border-right: 100px solid transparent;border-bottom: 100px solid transparent;border-left: 100px solid transparent;}
</style>
<div class="tri"></div>
四、外部样式表
外部样式表通过 标签引入,便于维护和复用样式:
示例代码:
<!-- 引入外部样式表 -->
<link rel="stylesheet" href="styles.css">
外部样式表示例 (styles.css):
/* 全局样式 */
* {color: aquamarine;
}/* 特定元素样式 */
#author {color: brown;
}