4

Pm Em Rem | news view

 3 years ago
source link: https://zsqk.github.io/news/2020-04-29-pm-em-rem.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

news view

在css中单位长度用的最多的是px、em、rem,这三个的区别是:

  px是固定的像素,一旦设置了就无法因为适应页面大小而改变。

  em和rem相对于px更具有灵活性,他们是相对长度单位,意思是长度不是定死了的,更适用于响应式布局。 对于em和rem的区别一句话概括:em相对于父元素,rem相对于根元素 rem中的r意思是root(根),这也就不难理解了

  • 子元素字体大小的em是相对于父元素字体大小

  • 元素的width/height/padding/margin用em的话是相对于该元素的font-size ```

我是父元素div

我是子元素p 我是孙元素span

div { font-size: 40px; width: 10em; /* 400px / height: 10em; / 400px / border: solid 1px black; } p { font-size: 0.5em; / 20px / width: 10em; / 200px / height: 10em; / 200px / border: solid 1px red; } span { font-size: 0.5em; / chrome有最小字体12px的限制所以这里为 12px / width: 10em; / 120px / height: 10em; / 120px */ }


### rem
rem是全部的长度都相对于根元素,根元素是谁?<html>元素。通常做法是给html元素设置一个字体大小,然后其他元素的长度单位就为rem。

html { font-size: 10px; } div { font-size: 4rem; /* 40px / width: 30rem; / 300px / height: 30rem; / 300px / border: solid 1px black; } p { font-size: 2rem; / 20px / width: 15rem; / 150px / height: 15rem; / 150px / } span { font-size: 1.5rem; / 15px / width: 10rem; / 100px / height: 10rem; / 100px */ } ```

This site is open source. Improve this page.

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK