Home >Web Front-end >CSS Tutorial >How Can You Use vh and vw Units in Cross-Browser Environments?
CSS3 introduced Viewport-percentage length units, vh and vw, providing a powerful tool for responsive layouts. However, browsers have not fully supported these units, particularly when it comes to font sizes.
To address this limitation, JavaScript and jQuery offer alternative solutions. One such solution involves converting vh and vw values to pixels on a window resize event.
The following jQuery plugin tackles this conversion task:
<code class="javascript">(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 , originalArguments = arguments , update = function() { if ( typeof props === 'string' || props instanceof String ) { if (originalArguments.length > 1) { var argumentsObject = {}; argumentsObject[originalArguments[0]] = originalArguments[1]; return _css.call(self, parseProps($.extend({}, argumentsObject))); } else { return _css.call( self, props ); } } else { return _css.call( self, parseProps( $.extend( {}, props ) ) ); } }; $win.resize( update ).resize(); return update(); }; }( jQuery, window ));</code>
With this plugin, you can use vh and vw units in your CSS as follows:
<code class="css">div { height: 50vh; width: 50vw; fontSize: 10vw; }</code>
While native browser support for vh and vw continues to improve, this JavaScript/jQuery solution provides a cross-browser workaround, allowing you to harness the power of these units for your responsive layouts.
The above is the detailed content of How Can You Use vh and vw Units in Cross-Browser Environments?. For more information, please follow other related articles on the PHP Chinese website!