如何在CSS中更改下划线的宽度

7

I have a cell in a table like this:

<td><b>Grand Total</b></td>

我需要在“Grand Total”文本下面添加一条线。我使用了text-decoration: underline;,它运行良好,但我需要更改下划线的颜色和粗细。我尝试使用text-decoration-color: red; 添加颜色,但它不起作用。请问如何解决这个问题?

你可以使用 border-bottom 属性来设置下划线的宽度和颜色。 - Ron537
9个回答

10

使用border-bottom来定义颜色码:

b {
    border-bottom: 1px solid red;
    padding: 0 0 4px;
}
<td><b>Grand Total</b></td>


5
最佳方法是使用 text-decoration-thickness CSS 属性。这里是指向文档的链接:链接。一个简单的代码示例如下所示:
text-decoration: underline solid black 2px;

这里的2pxtext-decoration-thickness,也就是下划线的宽度。

在所有浏览器中都支持,但在安卓的 Firefox 和 IE 中不支持。请参考 https://caniuse.com/?search=text-decoration-thickness。 - Fanky
1
@Fanky 现在在Firefox Android上也得到了支持,已经有大约一个月的时间了,所以可以说这是未来可靠的答案,应该会使其他方法过时。我之前完全不知道这个属性的存在,不用再使用旧的hack方法真是太好了。 - undefined

5

您无法修改underline标签的宽度。相反,可以采用border-bottom方法并根据需要更改其属性。

.underline {
  border-bottom: 5px solid red;
}
<table>
  <tr>
    <td><b class="underline">Grand Total</b></td>
  </tr>
</table>


4
使用伪元素像:before:after来控制下划线的长度。

td {
  position: relative;
}

td:after {
  content: '';
  position: absolute;
  width: 100%;
  display: block;
  height: 5px;
  background-color: red;
  bottom: -5px;
}
<table>
  <tbody>
    <tr>
      <td><b>Grand Total</b></td>
    </tr>
  </tbody>
</table>


它不会将整个文本下划线。 - MotKohn
要求是控制下划线的宽度。只需将宽度设置为100%,它就会在整个文本下面加上下划线。 - Dan Philip Bejoy
哦,我以为 OP 指的是厚度。你可能是对的。 - MotKohn

3

通常我使用这三个CSS属性来样式化下划线

设置下划线的粗细

text-decoration-thickness: 3px;

设置下划线的颜色

text-decoration-color: 红色;

偏移下划线

text-underline-offset: 5px;


2
你应该给你的特定行添加类或ID,例如:
HTML:
<td><b id="total">Grand Total</b></td>

CSS(层叠样式表):
#total {
  border-bottom: 1px solid red;
  padding: 0 0 4px;
}

2

来自这里

td {
  color: red;
  text-decoration: underline;
}

span {
  color: black;
  text-decoration: none;
}
<table>
  <tr>
    <td><b><span>Grand Total</span></b></td>
  </tr>
</table>


我该如何指定下划线的宽度?谢谢您的回答。 - Jibin
@Jibin 不太确定如何处理 - Carl Binalla
感谢您对 Carl Jan 的支持。 - Jibin

2
如果你要定位你的字母'b',可以使用背景渐变来调整线条的粗细和垂直位置。
例如:
b {
    background-image: linear-gradient(to bottom, #fdb514 50%, transparent 50%);
    background-position: 0px 0.9em;
    background-repeat: repeat-x;
    background-size: 1px 15px;
    display: inline;
}

非常好的解决方案。谢谢@Reece。 - Radu Bartan

0
td {
position: relative;
}

td::after {
content: '';
position: absolute;
width: 30%;
display: block;
height: 5px;
background-color: red;
bottom: -5px;
}

要控制宽度,只需将宽度从100%更改为您希望的任何值即可。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接