Search code examples
htmlcssimagecover

Header Image won't cover page width


I am continuing to practice with HTML and CSS. I am trying to make an image go the width of the page, centered below the header. For some reason, it won't work when I try options on stretching it. My guess is that there is an option I have yet to come across to do so.

CSS

#header {

height: 80px;
background-color: gray;
margin-bottom: 60px;


}

.container {

}

.MainImage {

background-image:url(computers.jpg);
height: 400px;
background-repeat: no-repeat;
width: 100%;

}

.MainImage img {

position: relative;
background-size: cover;

}

HTML

<body>

<div id = "header">
<div class = "nav">

    <!-- container-fluid gives full width container of whole viewport -->

    <div class = "container-fluid">


    <ul id = "nav" class= "text-left">
        <li><a href = "#"><strong>Home</a></li>
        <li><a href = "#">Technologies</a></li>
        <li><a href = "#">Programs</a></li>
        <li><a href = "#">Blog</strong></a></li>
    </ul>

    <ul id = "nav" class = "text-right">
        <li><a href = "#"><strong>Sign Up</a></li>
        <li><a href = "#">Sign In</a></li>
        <li><a href = "#">Contact</strong></a></li>
    </ul>

    </div><!-- end container-fluid-->
</div><!--end nav-->
</div> <!-- end header --> 



<div id = "Main">


    <div class = "MainImage">


    </div>


</div><!--end Main-->



</body>

http://jsfiddle.net/xehu1tg0/

UPDATE: my IE 10 image error

enter image description here


Solution

  • You need to add background-size: 100% auto; to your .MainImage class, like so:

    .MainImage {
        background-image:url(http://www.onlineuniversities.com/wp-content/uploads/improving-tech-literacy.jpg);
        height: 500px;
        background-repeat: no-repeat;
        background-size: 100% auto;
        width: 100%;
    }
    

    The height and width properties only affect the container element, not the background image itself.

    100% auto essentially means the image size should be 100% the width of its container, and the height should scale automatically with the width (where you see two values like this, the first almost always relates to the x axis, with the second relating to the y axis.)

    I hope that makes sense?

    Example: http://jsfiddle.net/w1020vu1/