Skip to content

Instantly share code, notes, and snippets.

@elclanrs
Created December 19, 2012 22:10
Show Gist options
  • Save elclanrs/4341016 to your computer and use it in GitHub Desktop.
Save elclanrs/4341016 to your computer and use it in GitHub Desktop.
Use CSS viewport units with jQuery
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="v2p.js"></script>
<style type="text/css" media="all">
body { margin: 0; }
div {
background: #fa7098;
}
</style>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<div>hello</div>
<script type="text/javascript" charset="utf-8">
$('div').css({
height: '50vh',
width: '50vw',
marginTop: '25vh',
marginLeft: '25vw',
fontSize: '10vw'
});
</script>
</body>
</html>
/*
* CSS viewport units with jQuery
* http://www.w3.org/TR/css3-values/#viewport-relative-lengths
*/
/*
* CSS viewport units with jQuery
* http://www.w3.org/TR/css3-values/#viewport-relative-lengths
*/
;(function( $, window ){
var $win = $(window)
, _css = $.fn.css;
function viewportToPixel( val ) {
var percent = val.match(/[\d.]+/)[0] / 100,
unit = val.match(/[vwh]+/)[0];
return (unit == 'vh' ? $win.height() : $win.width()) * percent +'px';
}
function parseProps( props ) {
var p, prop;
for ( p in props ) {
prop = props[ p ];
if ( /[vwh]$/.test( prop ) ) {
props[ p ] = viewportToPixel( prop );
}
}
return props;
}
$.fn.css = function( props ) {
var self = this,
update = function() {
return _css.call( self, parseProps( $.extend( {}, props ) ) );
};
$win.resize( update ).resize();
return update();
};
}( jQuery, window ));
Copy link

ghost commented Nov 13, 2017

How use margin: -20...?

// (...)
marginTop: -'25vh',
marginLeft: '-25vw',
// (...)

is ignored.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment