Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make CSS media query use the em size of the html document rather than the browser?

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;
    }
}

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?

like image 891
macrael Avatar asked Dec 31 '10 07:12

macrael


2 Answers

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).

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.

like image 146
Jukka K. Korpela Avatar answered Oct 14 '22 17:10

Jukka K. Korpela


From W3C (http://www.w3.org/TR/CSS21/syndata.html)
The 'em' unit is equal to the computed value of the 'font-size' property of the element on which it is used. The exception is when 'em' occurs in the value of the 'font-size' property itself, in which case it refers to the font size of the parent element.

html { font-size:1em; width:42em; }
body { font-size:1.6em; }

@media screen and (max-width:40em) {
    div#page { font-size:0.875em; } /* 14px font */
}

Note: 42em will probably never be 100% of the browser window's width. If you change the @media to act differently for different screen widths (max-width:1200px), (max-width:1024px) you'll probably get more of the effect I think you're after.

like image 45
Dawson Avatar answered Oct 14 '22 15:10

Dawson