Home > Article > Web Front-end > Mobile css unit 'vh” & 'vw”
1. Foreword:
Responsive web design is inseparable from percentages. However, CSS percentages are not the best solution for all problems. CSS width is relative to the width of the nearest parent element that contains it. But what if you just want to use the width or height of the viewport instead of the parent element?
2. "vh" & "vw":
vh: relative to the height of the window: the height of the window is 100vh.
vw: relative to the width of the window: the window width is 100vw.
'
3. Source code:
CSS:
.demo-1,.demo-2,.demo-3{margin-bottom:10px; padding:10px 0; line-height: 30px; color: #fff; text-indent: 10px;} .demo-1 strong,.demo-2 strong,.demo-3 strong{color:#fff !important;} .demo-1{width:10vw; background: #1ab5e3;} .demo-2{width:25vw; background: #FF5F09;} .demo-3{width:50vw; background: #28AF59;} .demo-4{position: fixed; z-index: 10; top: 0; left: 0; width: 150px; height: 100vh; color: #fff; background: rgba(0,0,0,.5);} .demo-4 span{position:absolute; top:50%; display:block; padding: 0 10px; -webkit-transform: translateY(-50%); transform: translateY(-50%);}
HTML:
<div class="demo-1">视窗的10%: <strong class="js-getVW1">0</strong></div> <div class="demo-2">视窗的25%: <strong class="js-getVW2">0</strong></div> <div class="demo-3">视窗的50%: <strong class="js-getVW3">0</strong></div> <div class="demo-4"><span>视窗的100%高度<br/>(看我!!!)</span></div> <p class="btn-normal">看我!!!看我...!!!我是浏览器视窗的宽度(你可以通过改变浏览器宽度看我的变化):<span class="js-viewWidth">0</span></p>
JS:
$(function(){ //视窗宽度改变函数 function resizeWindow(){ var viewWidth = window.innerWidth; $('.js-viewWidth').html(viewWidth); $('.js-getVW3').html(viewWidth/2); $('.js-getVW2').html(viewWidth/4); $('.js-getVW1').html(viewWidth/10); } //初始化 resizeWindow(); //浏览器视窗改变时调用上面定义的函数 $(window).resize(function(event) { resizeWindow(); }); });
Interested students can visit the original text: http://www.yuanbo88.com/article.html?rid =44.