零基础教你学前端 CSS表格
本次,我们来讲解应用 CSS 来装饰表格。
如何制作一个表格,我们在HTML课程中已经学习过了。现在,我们通过样式,让表格变得更加美观易用。
首先来学习如何定义表格边框。
要在CSS中指定表格的边框,可以使用 border 属性。我们来举个例子。
创建 tables.html 文件和 tables-style.css 文件。在 html 里构建基础代码,引入外部样式。
在 body 里编写 emmet 命令:table>(tr>th*2)+(tr>td*2)*3,填入一些文本。

HTML
<table>
<tr>
<th>千锋名师</th>
<th>最新作品</th>
</tr>
<tr>
<td>浠浠呀</td>
<td>《HTML+CSS前端入门》</td>
</tr>
<tr>
<td>陆荣涛</td>
<td>《Vite学习指南》</td>
</tr>
<tr>
<td>Kerwin</td>
<td>《Vue2+Vue3全套教程》</td>
</tr>
</table>
在浏览器里预览效果:表格的结构有了,还没有边框。大家还记得如何通过 html 属性定义边框吗?可以评论上告诉我。
现在,我们通过样式来给表格添加边框。定义群组选择器 table, th, td,声明样式:border: 1px solid。
再看效果,表格线出现了,可是外观上看,线条有点粗。是因为 table、th和td元素都有独立的边框。
CSS
table, th, td {
border: 1px solid;
}


可以应用 border-collapse 属性,把表格的边框折叠成一个单一的边框。
回到 CSS,再给 table 元素声明样式:border-collapse: collapse。
此时,表格线变细了。
CSS
table {
border-collapse: collapse;
}

当前表格看起来很小,如果我们需要一个横跨整个屏幕的表格,该如何实现呢?
回到CSS,再给 table 添加样式 width: 100%。
再看一下效果,表格横向撑满了整个屏幕。

接下来,我们来定义表格的宽度和高度。
width 和 height 属性用来定义表格的宽度和高度。我们来实验一下。
将 table 的 width 属性修改为 50%,再给 th 声明样式 height: 70px。
我们看,表格宽度缩小了一半,同时表头的高度也变大到 70px 了。
接下来,我们来设置表格的对齐方式。
text-align 属性用来设置 th 或 td 中内容的水平对齐方式,如居左、居右或居中对齐。默认情况下,th 元素的内容是居中对齐的,td 元素的内容是左对齐的。要使 td 元素的内容也居中对齐,可以使用text-align: center。举个例子:
回到CSS,给 td 添加样式:text-align: center。
此时,全部 td 里的内容在单元格里水平居中显示了。
要使内容左对齐,可以使用 text-align: left 属性。
比如将 th 元素的对齐方式改为左对齐。

CSS
th {
height: 70px;
text-align: left;
}

vertical-align 属性用来设置 th 或 td 中内容的垂直对齐方式。如顶部对齐、底部对齐或中间对齐。默认情况下,对于 th 和 td 元素,表格中内容的垂直对齐方式是中间对齐。举个例子:
回到 CSS,给 td 添加样式:height: 50px,vertical-align: bottom。
我们看, td 单元格里的内容垂直底部对齐了。

接下来,给表格添加内填充、水平分隔线、鼠标滑过高亮及颜色等样式。
要控制表格中边框和内容之间的空间,可以给 td 和 th 元素设置 padding 属性。
回到 CSS,先注释掉 th 和 td 的样式。定义选择器 th, td,声明样式:padding: 15px,text-align: left。
CSS
th, td {
padding: 15px;
text-align: left;
}
看一下效果,内容和边框线之间就具有了 15px 的填充。

接下来通过给 th 和 td 添加 border-bottom 属性,实现表格的水平分隔线效果。
注释掉原有的 border 属性,给 th 和 td 添加样式:border-bottom: 1px solid #ddd。
CSS
table, th, td {
/* border: 1px solid; */
}
th, td {
padding: 15px;
text-align: left;
border-bottom: 1px solid #ddd;
}
我们看,水平分隔线的表格效果就实现了。

在 tr 上使用 :hover 选择器,在鼠标移过时突出显示表格的行。
回到CSS,定义选择器 tr:hover,声明样式:background-color: coral。kerou
当鼠标滑过每一行时,当前行就高亮显示了。

我们也可以专门给某一行添加背景色,比如给 th 添加一个绿色背景。
再单独给 th 定义样式:background-color: #04AA6D,color: white;
CSS
th {
background-color: #04AA6D;
color: white;
}
这样,通过给 th 添加背景色,使表头的显示更加醒目了。

相关推荐
-
PHP8种变量类型的详细讲解2025-02-22 00:32:24
-
php+apache 和 php+nginx的区别2025-02-22 00:21:27
-
PHP:与workerman结合实现定时任务2025-02-22 00:15:57
-
Nginx的Rewrite规则与实例2025-02-22 00:15:39
-
MySql中身份证字段的简单脱敏介绍2025-02-22 00:15:36