CSS背景图片智能定位

加丹·L。

好的,我想做一些我认为很简单的事情,但是我似乎找不到方法。

我必须div(实际上是一个导航和一个主)和CSS像这样:

nav {
  float: left;
  width: 300px;
  height: calc(100vh - 3em);
}

main {
  height: calc(100vh - 3em);
  margin-left: 300px;
  background: url('../images/background.jpg');
}

footer {
  height: 3em;
}

HTML:

<html>
  <head>
  </head>
  <body>
    <nav>
    </nav>
    <main>
    </main>
    <footer>
    </footer>
  </body>
</html>

所以我想要背景图片是

  • 固定(滚动主键时不移动)
  • 以始终占据整个主要部分,但不会溢出到页边空白中,也不会像页边空白一样是主要部分的一部分(例如,当我尝试将图像居中时,它将居中于整个页面上,而忽略了页边空白)
  • 由于图像并不总是适合主要比率w / h,因此我希望它填充100%的宽度或高度,然后在另一个维度上溢出,但是...
  • 总是居中

这一切可能吗?我做了一个codepen:https ://codepen.io/cypherfirelair/pen/yLYNMKY

编辑:我发现了一种结合水平和垂直中心以及左侧和底部的偏移量的更好方法:背景位置:calc(50%+ 150px)calc(50%-2.5em);

Aymen TAGHLISSIA

这是您问题的解决方案,我只是更改了这两个元素:background-size: calc(100vw - 300px) auto;background-position: 300px;https : //codepen.io/Aypro18/pen/LYpVWMd

CSS:

* {
  margin: 0;
  padding: 0;
}

nav {
  float: left;
  width: 300px;
  height: calc(100vh - 3em);
  background-color: red;
}

main {
  height: calc(100vh - 3em);
  width:calc(100vw - 300px);
  margin-left:300px;
  background: url('https://s1.1zoom.me/big3/998/Spain_Scenery_Mountains_Forests_Cantabria_525299_4608x3456.jpg');
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-size: calc(100vw - 300px) auto;
  background-position: 300px;
}

footer {
  height: 3em;
  background-color: magenta;
}

HTML:

<html>
  <head>
  </head>
  <body>
    <nav>
    </nav>
    <main>
    </main>
    <footer>
    </footer>
  </body>
</html>

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章