使CSS媒体查询使用em大小的html文档而不是浏览器? [英] Make CSS media query use the em size of the html document rather than the browser?

查看:194
本文介绍了使CSS媒体查询使用em大小的html文档而不是浏览器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用媒体查询来根据窗口的宽度来更改元素的宽度(这允许我增加页面上的列数,而不改变列的宽度)。我想能够使用em而不是像素,这样一切都会正确,如果你改变你的字体大小。但是,如果我使用以下:

I'm trying to use media queries to change the width of an element in chunks based on the width of the window (this allows me to increase the number of columns on the page without the width of the columns changing). I'd like to be able to do this using em's instead of pixels so that everything will look right if you change your font size. However, if I use the following:

html {
    font-size: 12px; /* you could also use 75% if you want to be percent based.*/
}

@media screen and (min-width: 42em) {
    div#page {
        width: 42em;
    }
}

媒体查询将在窗口达到42 * 16px,我的浏览器(Safari)的默认字体大小,而div#页面的宽度将是42 * 12px,从html元素继承字体大小。我真的很想根据我使用的文本的宽度触发媒体查询,是否有办法使这项工作?

The media query will trigger when the minimum width of the window reaches 42 * 16px, the default font size for my browser (Safari), while the width of the div#page will be 42 * 12px, inheriting the font size from the html element. I'd really like for the media queries to trigger based on the width of the text I am using, is there a way to make that work?

推荐答案

否,您不能,因为在媒体查询中,媒体查询中的相对单位是基于初始值,这意味着单位从不基于声明的结果。例如,在HTML中,'em'单位是相对于'font-size'的初始值。(Media Query spec,clause 6 Units )。 font-size 的初始值code> medium ,它以依赖于浏览器的方式映射到物理大小(独立于您可以在CSS中设置的任何内容)。

No, you cannot, because in a media query, "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’." (Media Query spec, clause 6 Units). The initial value of font-size is medium, which is mapped to a physical size in a browser-dependent manner (independently of anything that you can set in CSS).

结论取决于您如何设置字体大小。如果您以像素为单位设置根元素的字体大小,则在媒体查询中使用像素也是符合逻辑的,因为使用 em 不会提供任何灵活性。如果你将根元素的字体大小设置为百分比,在媒体查询中使用 em 是有意义的,但你只需要考虑 em 表示浏览器的默认字体大小,您需要相应地选择 em 的乘数。

The conclusions depend on how you set the font size. If you are setting the font size of the root element in pixels, it is logical to use pixels in media queries, too, since the use of em would not provide any flexibility. If you set the root element’s font size as a percentage, it makes sense to use em in media queries, but you just need to take into account that em means the browser’s default font size there and you need to select the multiplier of em accordingly.

这篇关于使CSS媒体查询使用em大小的html文档而不是浏览器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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