mheonyae mheonyae - 5 months ago 13
HTML Question

Div same size as background image

So i have a div with a background image and i would like to make the div same size as the background image when i resize the window, so i can place some text in the center of it and i want to image to be responsive and so the div also.

my html for the image and text:

<div id="headerimg" class="header">
<h1>Welcome to my website</h1>
</div>


and my cc for it so far:

#headerimg{
background: url(http://images.huffingtonpost.com/2016-06-25-1466835058-3172856-DKCWebDesignBanner.jpg) no-repeat top center fixed;
background-size: cover;
width:100%;
}

.header{
height: 700px;
width: 100%;
margin: auto;
padding: 20%;
color: white;
text-align: center;
font-size: 50px;
}


i am just using a random image from google atm, ill replace later; but anyway.. how can i get the height to align whenever? Jquery maybe? -but im not realy familiar with jquery much...and yes, i want the div to be full width of the site all the time.

Answer

Would something like the following work for you:

https://jsfiddle.net/44k0320v/

I've updated your header width to use 50vw units, your example image has an aspect ratio of arount 2:1 meaning that if you want the div to maintain the correct height you need to set the height to be half of the viewport width (the measurement across the width of the screen is 100vw).

I have also updated the background image to have a size of 100% rather than cover so it's width will scale with the div.

I've also updated the font size to also use vw units.

New css below:

#headerimg{
    background: url(http://images.huffingtonpost.com/2016-06-25-1466835058-3172856-DKCWebDesignBanner.jpg) no-repeat top center fixed;
    background-size: 100%;
}

.header{
    box-sizing: border-box;
    height: 50vw;
    width: 100%;
    margin: auto;
    padding: 10% 20%;
    color: white;
    text-align: center;
    font-size: 3.5vw;
}