Konstantin Milyutin
Konstantin Milyutin

Reputation: 12356

Set size of the div to its background image

I have the following div on my page:

<div id="logo">
</div>

I would like to put a background image in this div:

#logo {
    background: url('logo3_light.jpg') no-repeat;
    width: 100%;
    height: auto;
}

But the image never shows up, because the height of the div is 0px.

I would like somehow to set the height of the wrapping div to the height of the scaled image. Is it possible?

Upvotes: 2

Views: 104

Answers (3)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123367

Since your original image is 1600x100 the height is 6.25% of its width, so you could try this

#logo {
    background: url(http://dummyimage.com/1600x100/000/fff.jpg) no-repeat;
    width: 100%;
    height: auto;
    padding-bottom : 6.25%; 
    background-size: cover; 
}

Example on codepen: http://codepen.io/anon/pen/EnJvI


Note: you can't simply use height: 6.25% because the height would be relative to the height of the parent element (the body element, whose height is not defined and it is 0, since your logo element is empty).

The padding-bottom use instead the width of the element itself to calculate the correct value (this technique is often used to keep the correct aspect ratio of videos on responsive design, fyi).

Anyway, I don't recommend to use empty markup for styling purpose: your logo should be a regular img element rather than a background, since a logo usually conveys information

Upvotes: 5

SimplyAzuma
SimplyAzuma

Reputation: 25594

Answer as found here: How to get div height to auto-adjust to background size?

<div style="background-image: url(http://your-image.jpg);">
    <img src="http://your-image.jpg" style="visibility:hidden"/>
</div>

Upvotes: 0

Grishka
Grishka

Reputation: 49

Unfortunately, there is no easy way. You could for example using javascript get url of the image, load it and get its dimensions, then set the dimensions to the div element.

What I would do, would, be just directly use tag to put image in the div. If you need additional content, you could put the content in another div inside the div you already have. Then the internal divs positioning can be set to absolute etc etc, hope it gives you idea how to do it

Upvotes: -1

Related Questions