Created
December 19, 2012 22:10
-
-
Save elclanrs/4341016 to your computer and use it in GitHub Desktop.
Use CSS viewport units with jQuery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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 )); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How use
margin: -20...
?is ignored.