Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set height to percent of width?

Tags:

css

This is what I want to do:

#sheet {
    margin: 0 auto;
    width: 100%;
    position: relative;
    height: calc(width * 1.3181818181818181818181818181818);
}

#sheet looks like this:

<div id="sheet">
    <img src="sheet1.svg"/>
</div>

The width of #sheet varies depending on the size of your browser. The height (presently) depends on the height of sheet1.svg. But I know the width to height ratio of sheet1.svg, and I would like to encode that in the CSS so that the #sheet div can be sized correctly before the SVG loads in. I need the div to be sized correctly, because I have some other code that depends on that...

CSS3 adds the calc() method, but I don't think you can do calculations based on other properties....so how can I dot his?

like image 883
mpen Avatar asked Nov 23 '13 02:11

mpen


People also ask

How do I make my viewport height 100%?

The Viewport Units To set an element's height equal to the screen's height, set its height value to 100vh.

How do you set the width and height of a form?

Select the form, then find the Properties pane in Visual Studio. Scroll down to size and expand it. You can set the Width and Height manually.


2 Answers

It can be done CSS only:

#sheet {
    position: relative;
    padding-top: 50%; /* Your percentage */
}
#sheet > img {
    position: absolute;
    height: 100%;
    left: 0;
    top: 0;
}

DEMO

It works because if you use a percentage in padding-top, it is relative to width. Then, you can use padding instead of height, using position: absolute to children in order to have a 0px tall parent.

like image 67
Oriol Avatar answered Nov 12 '22 17:11

Oriol


I've done it with a lot of jQuery hackery:

var $svg = $(document.getElementById('svg'));
var $sheet = $(document.getElementById('sheet'));

$svg.on('load', function() {
    $(window).off('.setSheetHeight');
    $sheet.css('height', '');
});

var setSheetHeight = function() {
    $sheet.height($sheet.width() * 1.3181818181818181818181818181818);
};

setSheetHeight();
$(window).on('resize.setSheetHeight orientationchange.setSheetHeight', _.throttle(setSheetHeight,100));

It immediately sets the sheet height to 1.32x its width. Once the SVG loads, the browser can compute the height of the sheet on its own, so I clear the height style and remove the event listener to save some CPU. I also throttle the event (using underscore) so it doesn't fire too often.

If you're curious, I then use the sheet height to resize some text on the page:

function setFontSize() {
    $('input:text').css('font-size',$sheet.height()/80);
}

setFontSize();
$(window).on('resize.setFontSize orientationchange.setFontSize', _.throttle(setFontSize, 100));

Since we can't set font-size relative to its container's height, apparently.

like image 30
mpen Avatar answered Nov 12 '22 18:11

mpen