css 为什么background属性不只应用于父容器?

xdnvmnnf  于 2022-12-24  发布在  其他
关注(0)|答案(3)|浏览(152)

我正在做一个大学网站从这个教程视频[Youtube].(https://www.youtube.com/watch?v=oYRda7UtuhA&t=2686s)我有这个部分大学校园部分在我的HTML当我的样式我的层类,使我的图像橙子背景.它是在整个页面的背景.
我不知道出了什么问题?
它不是散布在整个图像上,而是散布在整个网页上。我以为绝对位置属性只适用于'campus-col'类

.campus-col {
  flex-basis: 32%;
  border-radius: 10px;
  margin-bottom: 30px;
  position: 30px;
  overflow: hidden;
}

.campus-col img {
  width: 100%;
}

.layer {
  background: rgba(226, 0, 0, 0.7);
  height: 100%;
  width: 100%;
  position: absolute;
  top: 0;
  left: 0;
}
<div class="row">
  <div class="campus-col">
    <img src="https://www.pngall.com/wp-content/uploads/10/London-Transparent-PNG.png">
    <div class="layer">
      <h3>LONDON</h3>
    </div>
  </div>
</div>
dxpyg8gm

dxpyg8gm1#

如果您使用position: absolute,而没有任何包含position: relative的父文档,则绝对div将使用所有文档并随着滚动沿着移动。
您应该在.campus-col css中使用position: relative
more detailed document on position

cgyqldqp

cgyqldqp2#

你只需要改变位置:相对的而不是30 px在“.campus-col”

tf7tbtn2

tf7tbtn23#

您的". campus-col"具有flex-basis css属性,因此请确认您正在添加
显示:Flex;
css属性位于其父对象(". row")中。
还要将
相对位置
添加到**.校园列**中:
位置:相对;

    • 位置的元素:absolute**在最后一个相对位置元素中获取绝对位置,或者如果存在任何人,则将沿文档定位。

注意浏览器中的默认代理用户样式,没有样式的h3将从浏览器中接收默认样式,如下所示:

h3 {
    display: block;
    font-size: 1.17em;
    margin-block-start: 1em;
    margin-block-end: 1em;
    margin-inline-start: 0px;
    margin-inline-end: 0px;
    font-weight: bold;
}

因此,避免添加整个文档选择器:

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    text-decoration: none;
    list-style: none;
    outline: none;
    font-family: 'system-ui', sans-serif;
    font-weight: 300;
}
<!DOCTYPE html>
<html>
<head>
<style>
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    text-decoration: none;
    list-style: none;
    outline: none;
    font-family: 'Poppins', sans-serif;
    font-weight: 300;
}
.row {display: flex;}

.campus-col {
    position: relative;
    flex-basis: 32%;
    border-radius: 10px;
    margin-bottom: 30px;
    position: 30px;
    overflow: hidden;
}

.campus-col img{
    width: 100%;
}

.layer{
    background: rgba(226, 0,0,0.7);
    height: 100%;
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;
}
</style>
</head>
<body>

    <div class="row">
        <div class="campus-col">
            <img src="https://www.scaler.com/topics/images/mrinal_bhattacharya.webp">
            <div class="layer">
                <h3>LONDON</h3>
            </div>              
        </div>
    </div>

</body>
</html>

相关问题