移動端css單位之 “vh” & “vw”

來源:互聯網
上載者:User

一、前言:

響應式web設計離不開百分比。但是,CSS百分比並不是所有的問題的最佳解決方案。CSS的寬度是相對於包含它的最近的父元素的寬度的。但是如果你就想用視口(viewpoint)的寬度或者高度,而不是父元素的,那該怎麼辦?

二、“vh” & “vw”:

vh:相對於視窗的高度:視窗高度是100vh。

vw:相對於視窗的寬度:視窗寬度是100vw。

'

三、源碼:

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();  });});

有興趣的同學可以訪問原文:http://www.yuanbo88.com/article.html?rid=44。

  • 相關文章

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.