kossmoboleat
kossmoboleat

Reputation: 1951

Keep div aspect ratio when scaling, with inner images

I've been trying to build a menu with a fixed aspect-ratio that is scaled according to the size of the browser window. For this I am using a div with a background image like so: http://jsfiddle.net/keroben/9seaM/

I am using the following trick with padding-bottom to keep the aspect ratio:

padding-bottom:10%;

from Keeping/scaling DIV Ratio with percentages.

This works when resizing and keeps the aspect ratio. Now when I add the menu entries as images, I can't get it right that the height of the div stays the same (http://jsfiddle.net/keroben/aT3Vz/):

<div id="cool" >
    <img src="https://dl.dropboxusercontent.com/u/18518333/clear.png"/>
    <img src="https://dl.dropboxusercontent.com/u/18518333/clear.png"/>
    <img src="https://dl.dropboxusercontent.com/u/18518333/clear.png"/>
    <img src="https://dl.dropboxusercontent.com/u/18518333/clear.png"/>    
</div>

I've tried various other techniques too, but nothing works. I'm starting to think that I can only get this to work by setting the width and height directly in javascript, but I'd like to know if there's a more elegant solution...

Upvotes: 0

Views: 232

Answers (2)

Horatio Alderaan
Horatio Alderaan

Reputation: 3284

The issue is that the images change the height of the div. You can keep them from doing that by floating them. Also, if you want them to always fit within the container, you'll need to adjust the width of the images. So, something like this might work:

#cool img {
    float:left;
    width:25%;
    height: auto;
}

In the interest of creating semantic HTML, you may want to change your markup to something more like the following:

<nav>
    <ul>
        <li><a href="#"><img src="/my/cool/image.png" alt="Menu item 1"/></a></li>
        <li><a href="#"><img src="/my/cool/image.png" alt="Menu item 2"/></a></li>
        <li><a href="#"><img src="/my/cool/image.png" alt="Menu item 3"/></a></li>
    </ul>
</nav>

Upvotes: 2

Maciej Paprocki
Maciej Paprocki

Reputation: 1379

You should add this

#cool img{display:block;float:left;width:25%;height:auto;}

here you have example:

fiddle

Upvotes: 1

Related Questions