Html/Css - How to get an image to stretch 100% width of a container then display another image over it?

Craig van Tonder picture Craig van Tonder · Apr 14, 2012 · Viewed 80.4k times · Source

I am struggling with getting the layout of the header i have in mind together.

Here is the html so far:

<div id="header">
    <img src="/img/headerBg.jpg" alt="" class="headerBg" />
    <a href="/"><img src="/img/logo.png" alt="Logo" class="logo" /></a>
    <div id="loginBox">
        other code
    </div>
</div>

And the css so far:

#header {
    height: 130px;
    margin: 5px 5px 0 5px;
    border: #0f0f12 outset 2px;
    border-radius: 15px;
}

#loginBox {
    float: right;
    width: 23.5%;
    height: 128px;
    font-size: 75%;
}

.headerBg {

}

.logo {
    width: 50%;
    height: 120px;
    float: left;
    display: block;
    padding: 5px;
}

What I am trying to accomplish, is have the image "headerBg.jpg" display to 100% width of the div "header", so essentially it will be the background of the div itself. Then have the image "logo.png" and the div "loginBox" display above "headerBg.jpg".

The logo should be floated to the far left end and the loginBox floated to the far right as in the css.

With the image removed, the logo and div are placed correctly, but when the image is introduced they two floated items are placed after the image in the flow.

I have tried various additions and reconfigurations but none have proven to work out how I want them to.

I have added the image in the css as a background to the header div, but it does not stretch 100% that way.

Would anyone be able to provide some insight on this?

Also any tutorials covering things like this would be a great addition to my collection!

Thank you!

Answer

chadpeppers picture chadpeppers · Apr 14, 2012
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <title>Render this</title>
    <style type="text/css">
#header {
    position:relative;
    height: 130px;
    margin: 5px 5px 0 5px;
    border: #0f0f12 outset 2px;
    border-radius: 15px;
}

#loginBox {
    position:relative;
    float: right;
    width: 23.5%;
    height: 128px;
    font-size: 75%;

}

.headerBg {
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: -1;
}

.logo {
    position:relative;
    width: 50%;
    height: 120px;
    float: left;
    display: block;
    padding: 5px;
}
    </style>
</head>
<body>
<div id="header">
    <img src="img/headerBg.jpg" alt="" class="headerBg" />
    <a href="/"><img src="img/logo.png" alt="Logo" class="logo" /></a>
    <div id="loginBox">
        other code
    </div>
</div>

</body>
</html>