CSS Calc Viewport Units Workaround?
Before I answer this, I'd like to point out that Chrome and IE 10+ actually supports calc with viewport units.
FIDDLE (In IE10+)
Solution (for other browsers): box-sizing
1) Start of by setting your height as 100vh.
2) With box-sizing set to border-box - add a padding-top of 75vw. This means that the padding will be part f the inner height.
3) Just offset the extra padding-top with a negative margin-top
FIDDLE
div
{
/*height: calc(100vh - 75vw);*/
height: 100vh;
margin-top: -75vw;
padding-top: 75vw;
-moz-box-sizing: border-box;
box-sizing: border-box;
background: pink;
}
Viewport units, keeping aspect ratio?
I've made it work in IE10:
#elem {
width: 100vw;
height: calc((9/16)*100vw);
}
@media (min-aspect-ratio:16/9) {
#elem {
height: 100vh;
width: calc((16/9)*100vh);
}
}
Live demo: http://jsfiddle.net/C2ZGR/show/ (open in IE10 (preview version available for Windows 7); then re-size window, so that either the width, or height is very small)
I've used an element with the aspect ratio of 16:9, but the code can work for any aspect-ratio - just replace 16/9
, and 9/16
with your desired aspect ratio.
Btw, IE10 is the only browser in which this demo will work. Firefox/Opera don't implement viewport units yet, and the WebKit browsers currently have a bug where viewport units cannot be used inside calc()
.
Safari + CSS: using calc with vh does not work
Safari seems to be kind of buggy with viewport units in general, especially if you go back a version or two. The last time I tried to use vh/vw, I ran into similar issues and ended up making use of the v-unit javascript micro-lib, and it worked out very well.
CSS is rapidly catching up to javascript for things like layout calculations, but when it gets complex, supplementing your css with some light scripting often works better than CSS alone.
Related Topics
Check If a Browser Has Built-In HTML5 Form Validation
Height Is Not Correct in Flexbox Items in Chrome
How to Resolve 500 Internal Server Error
CSS Selector for No-Children-But-Not-Empty
How to Open Native iOS App (Calendar, Notes...) from a Link on Website
Multiple Select in Safari iOS 7
How to Stop <Div> Tags Interfering with Counters
Put Fixed Text on an Input Text Box
Convert Uppercase Letter to Lowercase and First Uppercase in Sentence Using CSS
How to Get Placeholder Text in Firefox and Other Browsers That Don't Support The HTML5 Tag Option
What Are The Default Values for Justify-Content & Align Content
How to Upload Multiple Files Using One File Input Element
Converting HTML Text into Plain Text Using Objective-C