PCR PCR - 3 months ago 8
CSS Question

Having trouble getting a background image to cover full width of screen

I want to have a background image to fill the entire width of the screen (not the height though) like on these websites: http://www.rokivo.com/ and
https://teemo.gg/

My current structure looks like this:

<header class="navbar navbar-default" role="navigation">

<div class="container">
Code for header
</div>

</header>

<div class="container">
Rest of page contents here
</div>


Am I going to have to wrap everything else in a div with class container and use that to specify the background-image? Or is there another way I can do this?

Answer

You could do something like the following:

HTML:

<header class="navbar navbar-default" role="navigation">

  <div class="header-content">
    Code for header
  </div>

</header>

<div class="container">
  Rest of page contents here
</div>

CSS:

header {
  width: 100%;
  background: url(https://unsplash.it/2000/1000/?blur) no-repeat center center;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

.header-content {
  padding: 5em 0;
  font-size: 2em;
  text-align: center;
}

So what's going on here? The wrapping header has a width of 100% in order to cover the entire width of the screen and has a background image as well. Also, it's set to no-repeat and centered vertically/horizontally, as well as background-size set to cover to allow as much of the image to show as possible.

On the .header-content, a padding is added to the div so that it is vertically centered.

The padding, text size, etc can be adjusted, but this should give you a general idea of how this effect is accomplished.

To see it in action, see this codepen.

Comments