如何为HTML标签设置背景颜色?

时间:2020-09-19 07:17:54

标签: html css background-color

我对html完全陌生。将背景颜色应用于标题元素时遇到问题。这样显示。

image

它不适用于ul元素。这是 我的代码:

* {
  margin: 0px;
  padding: 0px;
}

header h1 {
  text-align: center;
}

header ul {
  list-style: none;
  margin: 10px;
  float: right;
}

header ul li {
  display: inline;
  padding: 10px 10px 0 10px;
  border: 1px solid green;
}

header {
  background-color: hotpink;
}
<header>

  <h1>ABC reviews</h1>
  <ul class="log">
    <li>login</li>
    <li>sign up</li>
  </ul>

</header>

3 个答案:

答案 0 :(得分:0)

您只能更改一行

header ul {
    list-style: none;
    margin: 10px;
    direction: rtl; // old version is =>> float: right;
}

答案 1 :(得分:0)

background-color属性is not inherited from the parent tag

默认值:透明
继承:

另一方面,如在引用的部分中所见,默认值是 transparent ,这意味着子元素的背景颜色与底层 >元素。

请注意,基础元素父元素有何不同。

这就是为什么在您的代码中,h1背景色是 hotpink 。它的背景颜色尚未从header继承;它是透明的,并且幸运的是具有热粉色背景色,因为基础元素是header

但这不是一般规则。这就是您的列表所发生的情况,从header占用的空间中踢出(了解您的真实意图是否超出了此答案的范围),因此background-color: transparent显示为白色背景色。

根据您的实际需求,为了在子元素中使用与父元素相同的颜色,您可以确保父元素的高度也扩展到包括列表元素(如其他答案所述)。
否则,您可以在子元素样式中使用inherit关键字:

background-color: inherit;

Inherit关键字指定属性应从其父元素继承其值。

此解决方案(以及显式定义每个子元素的背景颜色...)在子对象的位置位于父对象的块区域之外的一般情况下也有效。

答案 2 :(得分:0)

您应该需要这样的东西:

* {
  margin: 0px;
  padding: 0px;
}

header{
  background-color: hotpink;
  position: relative;
}

header h1 {
margin: auto;
  text-align: center;
}

header ul {
  margin-right: auto;
  list-style: none;
  margin: 10px;
  position: absolute;
  top: 0;
  right: 0;
}

header ul li {
  display: inline;
  padding: 0 10px;
  border: 1px solid green;
}
<header>

  <h1>ABC reviews</h1>
  <ul class="log">
    <li>login</li>
    <li>sign up</li>
  </ul>

</header>