Billy J. Billy J. - 1 year ago 76
CSS Question

Need Image inside container to span full width of page and still act as a inline-block / block element

I am trying to have an image take the full width of the page while inside a div with a given width. I managed to do this by adding it as a background image and adding the following styles:

background-image: url(URL);
width: 100%;
height: 400px;
position: absolute;
left: 0;

However, the image is on top of all my other elements now, so I need to have the div display as a block or inline block element, but I'm not really sure the route to make this happen since when I apply those as styles nothing changes. Let me know if there is a good way to do what I'm trying to do. Thanks!

Here is a JSFiddle example of my problem:

Answer Source

So the reason your elements are falling beneath this element is because it taken out of the document flow. (As you may have read earlier.) Think of this as a box surrounded by pebbles. With the box in place, the pebbles sit finely around the box. However if we pull the box up, some of our pebbles fall beneath the box, and we can no longer see them. It's counted as what I like to call, a ghost element. It's undetected and untouchable by other elements.

(Sorry I know this is getting pretty winded.)

Essentially, what you're doing in your project is breaking it. If an element is 200 pixels wide, nothing inside of it should be more than 200 pixels wide.

Therefore the best workaround, i've provided in a JSFiddle shows you to set the parent element to no max-width. But to add container elements, inside of this container element wrapping the necessary elements, and to set their widths to whatever set width you need to.

  width: 100%;
  width: 200px
  width: 100%;

This allows the image element room to breath, and other elements the containment they need.

Also, an excellent link on positions:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download