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>
该类
.heart
有一个 background-colorgreen
,但它不起作用。我已经通过在网页上使用检查进行了检查,它绝对不会被任何其他 CSS 样式覆盖。这里发生了什么?使用的浏览器:谷歌浏览器
另外,你能向我解释一下有什么用:
top: 0px; right: 0px; bottom: 0px; left: 0px;
完全以及它是如何工作的。
解决方案
这里的问题是因为您在 CSS 中同时使用值 left、right 和 top、bottom,正如@Quentin 回答中所解释的那样,因为父级没有高度和宽度,这总是会导致heart
div 具有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>
推荐阅读
- python-3.x - Pandas 使用 iterrows 根据数据框列中的值创建具有团队名称的 csv 文件
- jdbc - 查看死信队列的标题
- flutter - 点击时大图 - 颤动
- php - 如何在 PHP 中将二进制数据从文件流式传输到 POST 正文
- java - 如何将 Intellij Idea 用于大约 5M LOC 的非常大的代码库。IintelliJ 无需手动操作即可自动理解项目结构
- json - 在不转义字符串的情况下将 BigQuery 提取到换行符分隔的 JSON
- java - Jolt 变换:从对象中提取嵌套数组
- excel - 如何根据另一列中的重复项修改列并在 Excel 中保留唯一值
- python - 创建具有不同名称和数字长度的变量
- c - 控制台不记录鼠标滚轮事件