如何在 <hr> 标签上设置背景颜色?

4
为什么以下代码中的 hr 标签元素没有设置为绿色?

hr {
  background-color: #00ff00;
}
<hr>


2
你看过这个问题吗:https://dev59.com/IGw15IYBdhLWcg3w0fAV? - David Thomas
1
可能是更改hr元素的颜色的重复问题。 - Josh
Josh似乎是正确的。默认情况下,您在hr中看到的黑色是其边框而不是背景,您需要设置border-color。只有当您给hr设置高度属性时,背景才会变得可见,并需要设置background-color - Lee Saxon
默认情况下,浏览器渲染hr标签的颜色来自CSS的border-bottom-color属性。您可以通过定位border-color属性来覆盖它。如果您只是给hr标签一个color属性,它甚至也可以工作,因为border-color默认从text-color继承。 - Deepak Yadav
3个回答

4

背景颜色只是为hr设置背景,通过应用内联样式,我们可以使它更容易实现。 https://jsbin.com/wuvolojuzu/

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <p>Hello</p>
  <hr color="red" width="100%" />
  <p>Hi</p>
</body>
</html>


3
您提供的代码可以正确设置背景颜色。但是,<hr>标签没有可见的背景,因此它似乎不起作用。您可能想要更改的是它的颜色而不是背景色:
hr {
   color: #00ff00;
}

这将使得 <hr> 标签的线条变成绿色。

如果没有生效,可能是其他元素使用了更高的层叠样式。这种情况下,您有几个选项:

1)增加 hr 选择器的特异性。

2)使用 !important 设置颜色:

hr {
   color: #00ff00 !important;
}

3) 在行内设置背景颜色:

<hr color="#00ff00" />

希望这可以帮助你!

1
通常情况下,您无法为 hr 标签设置 background-color。这是一个空元素。它必须有起始标签,但不能有结束标签。 hr 只接受 color 属性。例如:
<hr color="#00ff00" />

默认的 hr 值:
margin: 7px or 8px /*depend on box-modeling. */
border: 1px inset #000;
display: block;
/* No height */

标准用法:
margin-top: 10px; /* You can change margin height */
margin-bottom: 10px; /* You can change margin height */
border: 0; /* or border-top: 5px solid #00ff00 */
border-width: 5px 0 0 0;
border-style: solid;
border-color: #00ff00;

hr{
  margin-top: 15px;
  margin-bottom: 15px;
  border: 0;
  border-top: 5px solid #00ff00;
}
<html>
  <body>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
    <hr />
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
  </body>
</html>

我希望这可以帮到你。


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