移動端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。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    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.