首页 > 解决方案 > 为什么我的绝对定位元素不显示指定的背景颜色?

问题描述

我正在从以下位置调整代码:

https://www.freecodecamp.org/learn/responsive-web-design/applied-visual-design/create-a-more-complex-shape-using-css-and-html

<style>
  .heart {
    position: absolute;
    margin: auto;
    top: 0px;
    right: 0px;
    bottom: 0px;
    left: 0px;
    background-color: green;
  }
  .a{
    position: relative;
  }
</style>
<div class="a">
  <div class="heart">Hello</div>
</div>

  1. 该类.heart有一个 background-color green,但它不起作用。我已经通过在网页上使用检查进行了检查,它绝对不会被任何其他 CSS 样式覆盖。

    这里发生了什么?使用的浏览器:谷歌浏览器

  2. 另外,你能向我解释一下有什么用:

    top: 0px;
    right: 0px;
    bottom: 0px;
    left: 0px;
    

完全以及它是如何工作的。

标签: htmlcsscss-positionbackground-color

解决方案


这里的问题是因为您在 CSS 中同时使用值 left、right 和 top、bottom,正如@Quentin 回答中所解释的那样,因为父级没有高度和宽度,这总是会导致heartdiv 具有0px高度和0px宽度,以下代码片段解决了这个问题

<style>
  .heart {
    position: absolute;
    margin: auto;
    top: 0px;
    left: 0px;
    background-color: green;
  }
  .a{
    position: relative;
  }
</style>
<div class="a">
<div class="heart">Hello</div>
</div>

另一种解决方法:

.heart {
  position: absolute;
  margin: auto;
  top: 0px;
  left: 0px;
  background-color: green;
}
.a{
  position: static;
}
<div class="a">
  <div class="heart">Hello</div>
</div>

还有另一种方式:

.heart {
    position: absolute;
    margin: auto;
    top: 0px;
    left: 0px;
    right: 0px;
    bottom: 0px;
    background-color: green;
  }
 
  .a{
    position:relative;
    width:40px;
    height: 15px;
  }
<div class="a">
<div class="heart">Hello</div>
</div>


推荐阅读