在前端開發中,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;
}