【问题标题】:How do I position a div background-image absolute to the screen and not to the relative position of the div?如何将 div 背景图像绝对定位到屏幕而不是 div 的相对位置?
【发布时间】:2019-08-02 16:14:39
【问题描述】:

我有一个 div,我想绝对定位其背景,因为图像必须与绝对定位到 0,0 的背景图像对齐

    div{
      background-image: url(someImage.jpg);
      background-position: absolute 0px 0px; // either something like this or getting div's x & y values would help
    }

所以这是实际的代码 HTML

    <nav>
        <ul> 
            <li><a href="#about">About</a></li>
            <li><a href="#projects">Projects</a></li>
            <li><a href="#Services">Services</a></li>
            <li><a href="#contact">Contact</a></li>
            </ul>
    </nav>

css

        #header nav ul {
            background-image: url("../../images/bg.jpg");
            background-position:absolute 0 0; // this is the position which i would like to make absolute           
            background-repeat: no-repeat;       
        }

这就是我想要实现的目标

所以 nav 背景只显示在 NAV 区域,问题是 NAV 是垂直还是水平取决于屏幕大小和缩放,所以它没有固定的位置,但如果 NAVbackground 位置是固定的(绝对定位这将解决我的问题)

【问题讨论】:

  • 您将放置 div 以尝试将其对齐。 div 上的背景,你无能为力
  • 如果你不希望你的背景图片成为 div 的背景,听起来你应该把你的背景图片放在不同的元素中。
  • 问题是我的潜水动态移动,我需要它的背景与页面本身的背景对齐,如果我可以将 div 的位置本身引用为“背景位置:-self”会有所帮助.x -self.y;"或类似的东西
  • @JakeReece 我确实希望我的背景图片成为 div 的一部分,图片比 div 本身大并且背景的位置应该是固定的
  • 好的,看起来像背景附件:codepen.io/anon/pen/pMreao 使用相同的图像但颜色不同,你可以使用它和你自己的图像codepen.io/anon/pen/pMreao 除非我仍然误解

标签: css


【解决方案1】:

您可能正在寻找background-attachement:fixed

background-attachment CSS 属性设置背景图像的位置是在视口内固定,还是随着其包含块滚动。

测试示例

body {
  margin: 0;
  height: 150vh;
  background: 
    linear-gradient(to right, transparent 1vw, yellow 1vw, yellow 24vw, transparent 24vw), 
    linear-gradient(to bottom, transparent 10vmin, rgba(255,255,255,0.7) 10vmin ,  rgba(255,255,255,0.7) calc(20vmin + 100px) ,  rgba(100,50,0,0) calc(20vmin + 100px)) ,
    url(http://dummyimage.com/250x100/055/fff;)0 0 fixed;
  box-sizing:border-box;
}

div {
  float:left;
  margin: 15vmin 0 0 2.5vw;
  height: 80vh;
  width: 20vw;
  background: url(http://dummyimage.com/250x100/055/fff) 0 0 fixed;
}
div + div {
  height:100px;
  width:71vw
}
<div> <p>NAV here</p></div>
<div> <p>NAV or there</p></div>

【讨论】:

  • 正是我想要的。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-01
  • 1970-01-01
  • 2011-07-29
  • 2020-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多