之前写过一篇表格十字线聚焦效果的分享#11 ,但是用到了 JS,后来发现可以完全利用 CSS 来实现。
通过 td:hover
配合 ::before或::after
,并且将其高度设置无限高,同时改变 ::after
或 ::before的z-index
值为 -1(让高亮的背景色变为下层)。重要的一点,需要给 table
设置一个 overflow:hidden
,将伪元素溢出的高度截取掉。
show code~
<main> <table> <thead> <tr> <th></th> <th class="col">50kg</th> <th class="col">55kg</th> <th class="col">60kg</th> <th class="col">65kg</th> <th class="col">70kg</th> </tr> </thead> <tbody> <tr> <th class="row">160cm</th> <td>20</td> <td>21</td> <td>23</td> <td>25</td> <td>27</td> </tr> <tr> <th class="row">165cm</th> <td>18</td> <td>20</td> <td>22</td> <td>24</td> <td>26</td> </tr> <tr> <th class="row">170cm</th> <td>17</td> <td>19</td> <td>21</td> <td>23</td> <td>25</td> </tr> <tr> <th class="row">175cm</th> <td>16</td> <td>18</td> <td>20</td> <td>22</td> <td>24</td> </tr> <tbody> </table> </main>
table { overflow: hidden; } td, th { padding: 10px; position: relative; outline: 0; } tbody tr:hover { background-color: red; } td:hover::after, thead th:not(:empty):hover::after, td:focus::after, thead th:not(:empty):focus::after { content: ''; height: 10000px; left: 0; position: absolute; top: -5000px; width: 100%; z-index: -1; } td:hover::after, th:hover::after { background-color: red; }