首页 > 解决方案 > HTML 背景附件:已修复。滚动后背景被掩盖

问题描述

我基本上是在尝试创建一个背景图像,它将永远保持在固定位置。但是,似乎如果 div 内部有太多内容并且我向下滚动,图像仍然保持固定,但我向下滚动的次数越多就会“被覆盖”。

页面顶部的视图看起来完全没问题 向下滚动一点后,背景开始被覆盖(您可以看到图像仍然固定位置)

代码片段如下。我在内部 div 中添加了许多新行来显示问题

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Bootstrap 4 Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
    <style>

        html, body {
        height: 100%;
        margin: 0;
        }
        .bg{
        height: inherit;
        background-image: url("images/background.jpg");

        background-position: center center;
        background-repeat: no-repeat;
        background-size: cover;
        background-attachment: fixed;
        }

    </style>
</head>
<body>
<div class="bg">
    <div class="container">
    <h1>My First Bootstrap Page</h1>
    <p>This is some text.</p>
        <p>This is some text.</p>
        <p>This is some text.</p>
        <p>LOL</p>
        <p>This is some text.</p>
        <p>This is some text.</p>
        <p>This is some text.</p>
        <p>This is some text.</p>
        <p>This is some text.</p>
        <p>This is some text.</p>
        <p>This is some text.</p>
        <p>This is some text.</p>
        <p>This is some text.</p>
        <p>This is some text.</p>
        <p>This is some text.</p>
        <p>This is some text.</p>
        <p>This is some text.</p>
        <p>This is some text.</p>
        <p>This is some text.</p>
        <p>This is some text.</p>
        <p>This is some text.</p>
        <p>This is some text.</p>
        <p>This is some text.</p>
        <p>This is some text.</p>
        <p>This is some text.</p>
        <p>This is some text.</p>
        <p>This is some text.</p>
    </div>
</div>
</body>
</html>

标签: htmlcssbackground-image

解决方案


你需要添加overflow:scroll;.bg

bg{
    height: inherit;
    background-image: url(http://placekitten.com/200/300);
    background-position: center center;
    background-repeat: no-repeat;
    background-size: cover;
    background-attachment: fixed;
      overflow:scroll;//new selector added
    }

查看实时预览


推荐阅读