Skip to content Skip to sidebar Skip to footer

Keeping/scaling Div Ratio With Percentages

At the moment I have a layout that pulls a number of thumbnails into a grid - each is defined by a style that keeps them a fixed ratio, (roughly 16:9) which is defined by pixel dim

Solution 1:

Just a quick idea which might be useful for you. It is based on the fact that vertical padding/margin use the WIDTH of the parent box when it is set to percentages, so it is possible to resize a div relative its parent box

http://jsfiddle.net/xExuQ/2/

body,html { height:100%; }

.fixed-ratio-resize {
    width:          50%; /* child width  = parent width * percent */padding-bottom: 50%; /* child height = parent width * percent */height: 0;           /* well, it is not perfect :) */
}

​If you want to put some (non-background) content into this nicely resized box, then put an absolutely positioned div inside it.

Reference:

http://www.w3.org/TR/CSS2/box.html#margin-properties and http://www.w3.org/TR/CSS2/box.html#padding-properties says:

Margins: "The percentage is calculated with respect to the width of the generated box's containing block. Note that this is true for 'margin-top' and 'margin-bottom' as well. If the containing block's width depends on this element, then the resulting layout is undefined in CSS 2.1."

Paddings:"The percentage is calculated with respect to the width of the generated box's containing block, even for 'padding-top' and 'padding-bottom'. If the containing block's width depends on this element, then the resulting layout is undefined in CSS 2.1."

EDIT

http://jsfiddle.net/mszBF/6/

HTML:

<aclass="griditem"href="#"style="background-image: url(http://pic.jpg);"><spanclass="titles"><spanclass="name">Unicomp Studios</span><spanclass="title">Springs Buckling (2012)</span></span></a>

CSS:

.griditem {
    float: left;
    margin-right:  17px;
    margin-bottom: 17px;
    min-width:  100px; /* extremely narrow blocks ==> crap looking */width: 30%;
    background: blue no-repeat;
    background-size: contain; /* from IE9 only: https://developer.mozilla.org/en/CSS/background-size */border: 1px solid transparent; /* prevent .titles:margin-top's margin collapse */
}

.titles {
    /* <a> elements must only have inline elements like img, span.
       divs, headers, etc are forbidden, because some browsers will display a big mess (safari) */display: block; /* so display those inline elements as blocks */padding: 5px;
    margin: 0 auto;
    margin-top: 105%;
    background: yellow;
}

.titles > span {
    display: block;
}​

Solution 2:

I know this might not be the best solution, but

<html><styletype="text/css">#cool{
width:40%;
background:blue;
padding-bottom:10%;
}
</style><divid="cool" ></div></html>

Here Ive used padding-bottom, to maintain its height relative to its width. U can set padding-bottom as a percentage. Hope this helped.

Post a Comment for "Keeping/scaling Div Ratio With Percentages"