文字和背景是网页设计中最基本的元素,它们共同构成了网页的视觉基础。CSS 提供了丰富的属性来控制文字和背景的样式,使网页更加美观和易读。
文本属性用于控制文本的布局和外观。
color
属性设置文本的颜色:
h1 {color: #333;}p {color: rgb(51, 51, 51);}
text-align
属性设置文本的水平对齐方式:
h1 {text-align: center;}p {text-align: justify;}
常用值:
left
:左对齐(默认)right
:右对齐center
:居中对齐justify
:两端对齐text-decoration
属性设置文本的装饰:
a {text-decoration: underline;}
常用值:
none
:无装饰underline
:下划线overline
:上划线line-through
:删除线text-transform
属性控制文本的大小写:
h1 {text-transform: uppercase;}
常用值:
none
:不转换(默认)capitalize
:首字母大写uppercase
:全部大写lowercase
:全部小写text-indent
属性设置文本的首行缩进:
p {text-indent: 2em;}
letter-spacing
属性设置字符间距,word-spacing
属性设置单词间距:
h1 {letter-spacing: 2px;}p {word-spacing: 5px;}
white-space
属性控制空白符的处理方式:
pre {white-space: pre;}
常用值:
normal
:正常处理(默认)nowrap
:不换行pre
:保留空白符和换行符pre-wrap
:保留空白符和换行符,但允许自动换行pre-line
:合并空白符,保留换行符,允许自动换行字体属性用于控制文本的字体外观。
font-family
属性指定文本的字体:
body {font-family: Arial, Helvetica, sans-serif;}
Tips: 建议始终提供一个后备字体列表,以防用户系统上没有指定的字体。通用字体族(如 sans-serif、serif、monospace)应该放在列表的最后。
font-size
属性设置文本的大小:
h1 {font-size: 24px;}p {font-size: 16px;}
font-weight
属性设置文本的粗细:
h1 {font-weight: bold;}p {font-weight: normal;}
常用的值包括:
normal
:正常粗细(400)bold
:粗体(700)lighter
:较细bolder
:较粗font-style
属性设置文本的样式:
em {font-style: italic;}
常用值:
normal
:正常样式italic
:斜体oblique
:倾斜(与斜体类似,但通常由浏览器自动生成)line-height
属性设置文本的行高:
p {line-height: 1.5;}
Tips: 使用无单位的数值(如 1.5)设置行高是一种好习惯,因为它会根据元素的字体大小自动计算。
background-color
属性设置元素的背景颜色:
body {background-color: #f5f5f5;}
background-image
属性设置元素的背景图片:
header {background-image: url('header-bg.jpg');}
background-repeat
属性控制背景图片的重复方式:
body {background-image: url('pattern.png');background-repeat: repeat;}
常用值:
repeat
:水平和垂直方向都重复(默认)repeat-x
:只在水平方向重复repeat-y
:只在垂直方向重复no-repeat
:不重复space
:均匀分布,不裁剪round
:均匀分布,可能裁剪background-position
属性设置背景图片的位置:
header {background-image: url('logo.png');background-position: center top;}
常用值:
top
、right
、bottom
、left
、center
0% 0%
(左上角)、100% 100%
(右下角)0px 0px
(左上角)background-attachment
属性控制背景图片是否随页面滚动:
body {background-image: url('bg.jpg');background-attachment: fixed;}
常用值:
scroll
:背景图片随页面滚动(默认)fixed
:背景图片固定,不随页面滚动local
:背景图片随元素内容滚动background-size
属性设置背景图片的尺寸:
header {background-image: url('banner.jpg');background-size: cover;}
常用值:
auto
:自动(默认)cover
:覆盖整个容器,可能裁剪部分图片contain
:完全显示图片,可能有空白100px 200px
100% 50%
background
属性可以一次性设置多个背景属性:
header {background: #f5f5f5 url('logo.png') no-repeat center top fixed;}
这个简写属性的顺序是:background-color
、background-image
、background-repeat
、background-position
、background-attachment
。
让我们来创建一个漂亮的文章页面,练习文字和背景样式的应用。
这个练习包含了以下要点:
文字样式:
font-family
设置合适的字体font-size
控制文字大小line-height
设置行高color
设置文字颜色text-align
控制对齐方式letter-spacing
调整字间距背景样式:
background-color
设置背景颜色box-shadow
添加阴影效果border-radius
设置圆角布局技巧:
max-width
限制内容宽度margin
和 padding
控制间距border
添加分隔线你可以尝试修改这些样式,看看不同的效果。比如: