上一篇
html文字怎么设置
- 行业动态
- 2025-04-29
- 4337
使用`
标签或CSS设置,如
文本
文字基础样式设置
属性 | 说明 | 示例代码 | 效果 |
---|---|---|---|
font-family | 设置字体类型,可指定多个备选字体 | p { font-family: "微软雅黑", Arial, sans-serif; } | 优先使用”微软雅黑”,若不存在则用Arial或无衬线字体 |
font-size | 设置文字大小,支持像素(px)、百分比(%)、em等单位 | h1 { font-size: 32px; }<br>p { font-size: 1rem; } | 32像素标题,1倍根字体正文 |
color | 设置文字颜色,支持十六进制、RGB、颜色名 | span { color: #336699; }<br>div { color: rgb(51,102,153); } | 相同蓝色不同写法 |
font-weight | 设置字体粗细,数值400-700或关键字 | strong { font-weight: bold; }<br>em { font-weight: 600; } | 加粗显示与中等粗细 |
font-style | 设置字体样式,如斜体、正常 | i { font-style: italic; }<br>u { text-decoration: underline; } | 斜体与下划线效果 |
文字排版控制
属性 | 说明 | 示例代码 | 效果 |
---|---|---|---|
text-align | 水平对齐方式(左/右/居中/两端对齐) | div { text-align: justify; } | 文本两端对齐 |
line-height | 设置行高,支持数字倍数或具体单位 | p { line-height: 1.8; } | 8倍行距提升可读性 |
text-indent | 首行缩进,适用于段落 | p { text-indent: 2em; } | 首行空出2个字符宽度 |
letter-spacing | 字母间距调整 | h2 { letter-spacing: 3px; } | 字符间增加3像素空隙 |
text-transform | 文本大小写转换 | button { text-transform: uppercase; } | 按钮文字全大写 |
CSS样式应用方式
方式 | 说明 | 示例代码 | 适用场景 |
---|---|---|---|
内联样式 | 直接在标签中使用style 属性 | <span style="color:red;font-size:16px"> | 快速修改单个元素样式 |
内部样式表 | 在<style> 标签中定义样式规则 | <style>.red-text{color:#f00;}</style> | 统一管理页面样式 |
外部样式表 | 通过.css 文件引入样式 | <link rel="stylesheet" href="style.css"> | 多页面复用样式 |
特殊文本效果
属性组合 | 说明 | 示例代码 | 效果演示 |
---|---|---|---|
文字渐变 | 配合CSS渐变实现色彩过渡 | background: linear-gradient(45deg, red, yellow); -webkit-background-clip: text; color: transparent; | 彩虹色渐变文字 |
文字阴影 | 添加多层阴影增强立体感 | h1 { text-shadow: 2px 2px 0 #ccc, 4px 4px 0 rgba(0,0,0,0.3); } | 双层投影效果 |
文字换行控制 | 强制不换行或自动换行 | .nowrap { white-space: nowrap; overflow: hidden; }<br>.wrap { word-wrap: break-word; } | 超长文本省略号与自动换行 |
相关问题与解答
Q1:如何让中文网页在不同设备上都显示清晰的字体?
A1:建议使用CSS3的-webkit-font-smoothing: antialiased;
开启字体平滑,并优先选用屏显优化的字体(如”Microsoft YaHei”),对于移动端,可引入@media
查询适配不同像素密度,
body { -webkit-font-smoothing: antialiased; } @media (max-width: 768px) { body { font-size: 16px; } }
Q2:为什么设置了line-height
后文字垂直居中仍然有偏差?
A2:line-height
是基于字体高度计算的,若要精确垂直居中,需注意:
- 移除元素默认
padding
和margin
- 使用
display: flex; align-items: center;
进行容器级居中 - 示例代码:
.center-text { display: flex; align-items: center; justify-content: center; height: 200px;