Fixed Background Image
Asked Answered
P

3

5

I am curious to know how to create a background image in a div that is fixed. When you scroll down (or up) the image stays but the content flows over the div. Here is a site that does what I am trying to explain, to give you a better idea on what I am trying to describe. jWebMedia I've always thought sites like this were really attractive and wanted to know how to develop it. If you know of any good articles that cover this, that would be great.

Thanks for all your help!

Photomultiplier answered 16/2, 2015 at 21:21 Comment(0)
D
8
background:url('http://yoururl');    
background-size: cover;
background-attachment: fixed;
Disordered answered 16/2, 2015 at 21:29 Comment(1)
Perfect. Exactly what I was trying to accomplish. Thank you for your help.Photomultiplier
T
2

Fixed positioned elements

fixed The element is positioned relative to the browser window

/*only for this sample*/
body{
  margin:0;
}
div{
  width:100%;
  height:1000px;
  background:green;
}
nav{
  position:fixed;
  top:0;
  width:100%;
  height:40px;
  background:grey;
}
<div>
<nav></nav>
</div>

Fixed Background Image

CSS background-attachment Property

fixed The background is fixed with regard to the viewport

/*only for this sample*/
body{
  margin:0;
}

.fixed{
  width:100%;
  height:2000px;
  background-image:url(http://assets3.whicdn.com/assets/registration/reg_wall/Header-Find-your-inspiration.jpg);
  background-size:cover;
  background-attachment:fixed;
}
.scroll{
  position:absolute;
  width:50px;
  height:50px;
  margin:20px;
  background:orange;
}
<div class="fixed">
  <div class="scroll"></div>
</div>
Telescopic answered 16/2, 2015 at 21:31 Comment(0)
F
0

These are literally just what you said already in the question title – fixed background images.

background-attachment:fixed fixes the background image in regard to the viewport – and so when you scroll an element that has such a background image in and out of the viewport, that generates this effect, simple as that.

Fulgurous answered 16/2, 2015 at 21:35 Comment(5)
background-position: fixed doesn't exist.Acanthus
@user3790069: You’re right, I meant background-attachment of course. Edited.Fulgurous
@mitch: Well then what exactly do you mean? Especially since you asked “I am curious to know how to create a background image in a div that is fixed” and now have accepted the answer that pretty much does that.Fulgurous
@CBroe You are correct, apologies. I thought there was more to the CSS but after I tinkered around with the CSS all I needed was background-attachmentPhotomultiplier
As I said, it’s actually pretty simple. The background-size property mentioned in the accepted answer does come in handy though, when you want background images to be resized automatically to fit element dimensions, so you might want to read up on the possibilities that offers as well (developer.mozilla.org/en-US/docs/Web/CSS/background-size)Fulgurous

© 2022 - 2024 — McMap. All rights reserved.