首页 文章

向div添加边距不会移动背景图像的位置

提问于
浏览
1

我试图将div的背景图像与div的顶部对齐,但是它继续将它对齐到父div或整个页面的顶部(我不确定哪一个,但我认为它是页)

JSFiddle:https://jsfiddle.net/Minecraft_Percabeth/1wbuduze/2/

#bottom div的背景图像应该显示在它们的顶部,而顶部则与#wrap div的顶部对齐 . Edit: 图像也应该保持在向下滚动的位置,这就是我目前正在使用固定的原因 .

将margin-top更改为0以查看我的意思 .

<div id="wrap">
    <div id="bottom"></div>
</div>

#wrap {
    background-color: yellow;
    height: 500px; width: 500px;
    position: absolute;
}
    #bottom {
        background: blue url("http://i.imgur.com/BsTVroc.jpg") fixed center top;
        height: 400px; width: 500px;
        margin-top: 100px;
    }

2 回答

  • 1

    fixed
    background: blue url("http://i.imgur.com/BsTVroc.jpg") fixed center top;
    background-attachment: fixed; 的简写
    这就是为什么背景图像固定在顶部"the page" .
    如果没有此属性,背景图像将移至 margin-top: 100px;

    Edit:

    要垂直移动背景图像,您可以使用 background-position: center XY%; 并再次添加 background-attachment: fixed;

    #bottom {
        background-image: url("http://i.imgur.com/BsTVroc.jpg");
        background-repeat: no-repeat;
        background-position: center 20%;
        background-attachment: fixed;
        height: 400px;
        width: 500px;
        margin-top: 100px;
    }
    #wrap {
        background-color: #737373;
        height: 500px;
        width: 500px;
        position: absolute;
    }
    
    <div id="wrap">
        <div id="bottom"></div>
    </div>
    
  • 1

    您可以使用 background-position: center 100px; - 这会将背景图像向下移动100px .

相关问题