Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CSS 相对长度 #6

Open
mbaxszy7 opened this issue Jun 17, 2020 · 0 comments
Open

CSS 相对长度 #6

mbaxszy7 opened this issue Jun 17, 2020 · 0 comments
Labels

Comments

@mbaxszy7
Copy link
Owner

整理一下 CSS 相对长度

em

  • 1em 等于当前元素的字号,其准确值取决于作用的元素
  • 当设置 padding、height、width、border-radius 等属性时,使用 em 会很方便。这是 因为当元素继承了不同的字号,或者用户改变了字体设置时,这些属性会跟着元素均匀地缩放
  • 使用 em 定义字号时, font-size 是根据继承的字号(父元素)来计算的
<style>
  .par {
    font-size: 16px;
  }
  .chi {
    font-size: 2em;
    padding: 2em;
  }
</style>

<div class="par">
  cdcdcdcdcdc
  <div class="chi">
    dcdcdc
  </div>
</div>

div.chi computed:
WeChat2b572ea4e182a3806e2e75e2f4766852

rem

  • rem 是 root em 的缩写。rem 不是相对于当前元素,而是相对于根元素的单位。不管在文档的什么位置使用 rem,1.2rem 都会有相同的计算值:1.2 乘以根元素的字号
  • 拿不准的时候,用 rem 设置字号,用 px 设置边框,用 em 设置其他大部分属性

视口的相对单位

  • vh:视口高度的 1/100。(ios safari 100vh bug, 用js 的 window.innerHeight 解决
  • vw:视口宽度的 1/100。
  • vmin:视口宽、高中较小的一方的 1/100。
  • vmax:视口宽、高中较大的一方的 1/100。
  • 如何使用 vw 定义字号:

如果给一个元素加上 font-size: 2vw 会发生什么?
在一个 1200px 的桌面显示器上,计算值为 24px(1200 的 2%)。在一个 768px 宽的平板上,计算值约为 15px(768 的 2%)。这样做的好处在于元素能够在这两种大小之间平滑地过渡,这意味着不会在某个断点突然改变。当视口大小改变时,元素会逐渐过渡 。
不幸的是,24px 在大屏上来说太大了。更糟糕的是,在 iPhone 6 上会缩小到只有 7.5px
0.5em 保证了最小字号,1vw 则确保 了字体会随着视口缩放。这段代码保证基础字号从 iPhone 6 里的 11.75px 一直过渡到 1200px 的浏 览器窗口里的 20px。可以按照自己的喜好调整这个值:
:root { font-size: calc(0.5em + 1vw); }

https://www.manning.com/books/css-in-depth

@mbaxszy7 mbaxszy7 added the css label Jun 28, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant