Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Calc Viewport Units Workaround?

From what I've seen in other answers, CSS viewport units can't be used in calc() statements yet. What I would like to achieve is the following statement:

height: calc(100vh - 75vw) 

Is there some workaround way I can achieve this using purely CSS even though the viewport units can't be used in the calc() statement? Or just CSS and HTML? I know I can do it dynamically using javascript, but I'd prefer CSS.

like image 634
golmschenk Avatar asked Jan 20 '14 00:01

golmschenk


People also ask

Can I use Calc for margin CSS?

You can use calc() anywhere where you would use numeric values (e.g.: width, max-height, margin-left, …)

How do I get the width of a viewport in CSS?

You can use the window. innerHeight property to get the viewport height, and the window. innerWidth to get its width. let viewportHeight = window.

Can I use VH for width?

Moving to relative units to express length and using vh and vw style settings lets you control the widths and heights of elements no matter the viewport size. You can also use percentage-based units, but keep in mind that they're based on the parent element, while vh and vw style units are based on the viewport.

What is VW and VH in CSS?

To reiterate, VH stands for “viewport height”, which is the viewable screen's height. 100VH would represent 100% of the viewport's height, or the full height of the screen. And of course, VW stands for “viewport width”, which is the viewable screen's width.


1 Answers

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; } 
like image 187
Danield Avatar answered Sep 21 '22 03:09

Danield