在媒体查询和宽度中使用rem单位 [英] Using rem units in media queries and as width

查看:75
本文介绍了在媒体查询和宽度中使用rem单位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Google Chrome(或Firefox)中使用rem单元时,结果出乎意料.我设置了一个页面,其根字体大小设置为10px,以使其更容易将基于像素的设计转换为html/css.

When using rem units in Google Chrome (or firefox), the result is unexpected. I'v set up a page with the root font-size set to 10px to make it easier the translate a pixel based design to html/css.

这是我的CSS.我的期望是页面上有一个500像素宽的框,如果屏幕宽于500像素,则背景应该变成红色.

This is my css. My expectation would be a page with one 500px wide box and if the screen is wider than 500px the background should turn red.

html {
font-size: 10px;
}

@media screen and (min-width: 50rem){
  body{
    background-color: red;
  }
}

.test{
  width: 50rem;
  background: black;
  height:100px;
}

但是,尽管两个值均定义为50rem,但结果是一个500像素宽的框,该页面在800像素处变为红色.

But, despite both values being defined as 50rem, the results is a 500px wide box with the page turning red at 800px.

https://jsfiddle.net/tstruyf/puqpwpfj/4/

我在做什么错?为什么呢?

What am I doing wrong or why is this?

推荐答案

您没有做错什么,这就是媒体查询中rem起作用的方式.按照规范:

You're not doing anything wrong, this is how rem in media queries are meant to work. As per the spec:

媒体查询中的相对单位基于初始值,即 表示单位永远不会基于声明的结果.为了 例如,在HTML中,em单位是相对于的初始值的 字体大小,由用户代理或用户的首选项定义,而不是 页面上的任何样式.

Relative units in media queries are based on the initial value, which means that units are never based on results of declarations. For example, in HTML, the em unit is relative to the initial value of font-size, defined by the user agent or the user’s preferences, not any styling on the page.

因此,应用于基本字体大小的任何样式都不会影响媒体查询的计算.

So any styling you apply to the base font size doesn't have an effect on the media query calculation.

这是规范的相关部分.

如果您真的想使用rem并让他们使用10px的字体大小,则可以随时编写SASS mixin为您进行转换.除此之外,在媒体查询中坚持使用px可能会减少混乱.

If you really want to use rem and have them use a font-size basis of 10px, you could always write a SASS mixin to do the conversion for you. Other than that, it might be less confusing to stick with px for media queries.

这篇关于在媒体查询和宽度中使用rem单位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆