Вопрос

So, I have a website using lots of "ems" for fonts, they're literally everywhere. I managed to replace them all with rems, and now my media queries doesn't seem to be working as I've been changing my root font-size in them.

Here's the HTML:

<div id="em">
   <h1>EMs are better?</h1>
    <p>A text.</p>
</div>

<div id="rem">
   <h1>REMs aren't?</h1>
   <p>Sad panda.</p>
</div>

And CSS:

body {
    font-size: 14px;
}

div {
    margin: 10px;
    padding: 20px;
    text-align: center;
    background: #efefef;
}

#em h1 { font-size: 2em; }
#em p { font-size: 1em; }

#rem h1 { font-size: 2rem; }
#rem p { font-size: 1rem; }

@media screen and (max-width: 500px) {
  body {
    font-size: 6px;
    background: red;
  }
}

Try resizing window to see what happens, REM box doesn't seem to change at all...

http://jsfiddle.net/Q5vSC/

Это было полезно?

Решение

Rem units are based off the font size of the html element, not the body.

Your css would change to this:

html { // changed from body to html
    font-size: 14px;
}

div {
    margin: 10px;
    padding: 20px;
    text-align: center;
    background: #efefef;
}

#em h1 { font-size: 2em; }
#em p { font-size: 1em; }

#rem h1 { font-size: 2rem; }
#rem p { font-size: 1rem; }

@media screen and (max-width: 500px) {
  html { // changed from body to html
    font-size: 6px;
    background: red;
  }
}

Notice we target the html element in the first line and in the media query.

Here is your jsfiddle modified to work with rems.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top