CSS 测量单位: px, rem, em, vw, vh, %

浏览器支持的 CSS 单位总共有15种,但是常用的只有 6 种:

px

px 像素 : 是绝对单位。rem, em, vw, vh, % 是相对单位。使用 px 定义的大小固定,在所有的屏幕上看起来都一样。实际可以用来设固定的 border 宽度等等。绝对单位和相对单位都有各自的用处,没有好坏之分。

vw 和 vh

vwvh 分别相对于屏幕(严格来说是 viewport,窗口)的宽和高。例如,50vw 是屏幕宽度的一半,50vh 是屏幕高度的一半,依此类推。

%

% 相对于父元素,假如当前元素宽度为 50%, 而它的父元素宽度为 50vw,那么此元素的实际宽度为 50% * 50vw = 25vw,所以实际宽度为屏幕宽度的 1/4, 依此类推。设置字体大小时也是。

如果将元素的字体大小设置为百分比,它将是父元素字体大小的百分比。 如果对宽度值使用百分比,它将是父元素宽度的百分比。
if you set an element’s font-size as a percentage, it will be a percentage of the font-size of the element’s parent. If you use a percentage for a width value, it will be a percentage of the width of the parent.

rem

rem 中的 r 指的是 root 元素,即 <html> 元素。rem 是相对于 <html> 元素的字体大小的单位。所有的浏览器的<html> font-size 默认都是 16px,因此 4rem 对应 64px, 但是由于此数字 16 用于计算不那么方便,实际应用中可以使用一个小技巧:

html {
    /* 62.5% of 16px = 10px */
    font-size: 62.5%;
}

于是 16rem 马上就可以知道对应 160px
但是如果像下面这样直接设基本的字体大小为10px

html {
    font-size: 10px;
}

那么rem大小将会固定为10px,浏览器用户将无法按需放大或者缩小字体。
The main reason I don’t declare html { font-size: 10px; } is that if a visually impaired user has reset their base browser size (up or down), I want to respect that, so I want my site’s typography to scale proportionally to his default browser settings.

em

em 一般情况下相对于父元素的字体大小。

-相对于
em对于印刷属性如 font-size, 相对于父元素字体大小。而对于其他属性如 width, 则是相对于当前元素自己的字体大小.

如下的例子,先设 font-size,然后又设 width = 3em:

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="normalize.css" />
    <style>
        .child {
            font-size: 123px;
            width: 3em;
            border: 1px solid blue;
        }
    </style>
</head>
<body>
    <button>text</button>
    <div class="box parent">
        <div class = "box child">
            div-2
        </div>
    </div>
</body>
</html>

那么 width 实际将是 369px 如下图所示。不设此 font-size,width 将是 48px。
在这里插入图片描述
em 用于进行扩展或缩放时非常有用。

em,rem,%, 这几个相对单位,都可以用来设置元素的宽和高,以及字体大小。


省略。。。。。。。。。。。。。。。。。。

  1. https://stackoverflow.com/questions/32530787/what-is-the-root-element-for-rem
  2. https://stackoverflow.com/questions/24542508/default-html-font-size
  3. https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Values_and_units
  4. https://stackoverflow.com/questions/28988445/css-62-5-why-do-developers-use-it
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值