css字体样式代码

时间:2025-03-28 13:16:14 计算机

CSS字体样式代码主要用于控制网页文本的显示效果,以下是核心属性及代码示例:

一、基础字体样式属性

font-family

指定字体家族,如Arial、Times New Roman、Helvetica等。可同时设置多个字体作为后备,例如:

```css

p {

font-family: "微软雅黑", sans-serif;

}

```

若首选字体不可用,浏览器将尝试sans-serif等通用字体。

font-size

设置字体大小,常用像素(px)或相对单位(em、rem):

```css

h1 {

font-size: 2.5em; /* 相对于父元素字体大小 */

}

```

font-weight

控制字体粗细,包括normal(正常)、bold(加粗)、lighter(细体)等:

```css

strong {

font-weight: bold;

}

```

font-style

设置字体样式,如italic(斜体)、oblique(倾斜体):

```css

a {

font-style: italic;

}

```

color

定义字体颜色,支持十六进制、RGB或颜色名称:

```css

.highlight {

color: FF5733; /* 十六进制 */

/* 或者 */

color: rgb(255, 87, 51);

/* 或者 */

color: red;

}

```

二、扩展字体样式属性

text-align

文本对齐方式,如left、center、right:

```css

p {

text-align: center;

}

```

line-height

行高设置,单位为px或em:

```css

pre {

line-height: 1.5;

}

```

text-transform

文本转换,包括capitalize(首字母大写)、uppercase(全大写):

```css

.title {

text-transform: uppercase;

}

```

text-decoration

文本装饰,如underline(下划线)、line-through(删除线):

```css

a {

text-decoration: underline;

}

```

三、字体回退机制

当首选字体不可用时,浏览器会按以下顺序尝试备用字体:

1. 指定字体(如"Arial")

2. sans-serif(无衬线字体)

3. serif(衬线字体)

四、示例综合应用

```css

body {

font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;

font-size: 16px;

color: 333;

line-height: 1.6;

}

h1 {

font-size: 2.5em;

color: 0056b3;

text-align: center;

}

a {

color: 007bff;

text-decoration: none;

font-weight: bold;

}

a:hover {

text-decoration: underline;

}

```

通过组合使用这些属性,可以灵活控制网页文本的视觉呈现。