Home  >  Article  >  Web Front-end  >  How Can You Use vh and vw Units in Cross-Browser Environments?

How Can You Use vh and vw Units in Cross-Browser Environments?

DDD
DDDOriginal
2024-11-03 04:39:30568browse

How Can You Use vh and vw Units in Cross-Browser Environments?

vh and vw Units: Cross-Browser Implementation with JavaScript/jQuery

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.

jQuery Plugin

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>

Usage

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>

Conclusion

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn