CSS(Cascading Style Sheets)是用于网页样式和布局的样式表语言。其基本语法如下:
选择器 { 属性1: 值1; 属性2: 值2; /* 更多属性和值 */ }
- 选择器:用于选择要应用样式的HTML元素。
- 属性和值:规定元素的样式,如颜色、尺寸、字体等。
CSS 引入方式
- 内部样式表:使用
<style>
标签在HTML文档头部定义样式。
<head> <style> /* CSS 样式规则 */ </style> </head>
- 外部样式表:将样式规则保存在一个独立的.css文件中,然后在HTML中引入。
<head> <link rel="stylesheet" type="text/css" href="styles.css"> </head>
- 内联样式:在HTML元素上使用
style
属性定义样式。
<div style="属性: 值;"> <!-- 内联样式 --> </div>
选择器
基本选择器
- 元素选择器:选择指定类型的元素。
p { /* 样式规则 */ }
- 类选择器:选择具有指定类名的元素。
.button { /* 样式规则 */ }
- ID 选择器:选择具有指定ID的元素。
#header { /* 样式规则 */ }
- 属性选择器:选择具有指定属性的元素。
input[type="text"] { /* 样式规则 */ }
伪类选择器
- :hover:选择鼠标悬停的元素。
a:hover { /* 样式规则 */ }
字体相关属性
- font-family:定义字体类型。
body { font-family: Arial, sans-serif; }
- font-size:定义字体大小。
h1 { font-size: 24px; }
- font-weight:定义字体粗细。
strong { font-weight: bold; }
文本相关属性
- color:定义文本颜色。
p { color: #333; }
- text-align:定义文本水平对齐方式。
h2 { text-align: center; }
- line-height:定义行高。
p { line-height: 1.5; }
列表
- list-style-type:定义列表项标志的类型。
ul { list-style-type: square; }
- list-style-image:定义自定义列表项标志的图片。
ul { list-style-image: url('bullet.png'); }
背景
- background-color:定义背景颜色。
header { background-color: #0073e6; }
- background-image:定义背景图片。
section { background-image: url('background.jpg'); }
精灵图
雪碧图(CSS精灵图)是将多个图像合并到一个图像中,以减少HTTP请求。使用background-position
属性来选择显示图像的特定部分。
.icon { background-image: url('sprites.png'); background-position: -20px -40px; width: 16px; height: 16px; }
浮动
- float:使元素浮动到容器的左侧或右侧,文本和其他内容环绕它。
.float-left { float: left; }
清除浮动的方法
为了防止浮动元素引起的布局问题,可以使用清除浮动的方法,如:
.clearfix::after { content: ""; display: table; clear: both; }
然后将.clearfix
类添加到包含浮动元素的容器。
定位(4种)
- static:元素在文档中正常流动。
div { position: static; }
- relative:相对于元素自身的位置进行定位。
button { position: relative; top: 10px; left: 20px; }
- absolute:相对于最近的已定位祖先进行定位。
div { position: absolute; top: 0; left: 0; }
- fixed:相对于视口进行定位,元素不随页面滚动而移动。
header { position: fixed; top: 0; left: 0; }
内外边距
- padding:定义元素内部内容与边框之间的距离。
div { padding: 10px; }
- margin:定义元素与相邻元素之间的距离。
p { margin: 20px; }
盒子模型
每个元素由内容区、内边距、边框和外边距组成,构成盒子模型。你可以使用width
和height
属性控制内容区的大小,同时可以使用内边距、边框和外边距来调整元素的整体尺寸和间距。
.box { width: 200px; height: 100px; padding: 10px;