Why em instead of px?

后端 未结 15 1040
闹比i
闹比i 2020-11-22 06:38

I heard you should define sizes and distances in your stylesheet with em instead of in pixels. So the question is why should I use em instead of px when defining styles in c

15条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 07:31

    The reason I asked this question was that I forgot how to use em's as it was a while I was hacking happily in CSS. People didn't notice that I kept the question general as I wasn't talking about sizing fonts per se. I was more interested in how to define styles on any given block element on the page.

    As Henrik Paul and others pointed out em is proportional to the font-size used in the element. It's a common practice to define sizes on block elements in px, however, sizing up fonts in browsers usually breaks this design. Resizing fonts is commonly done with the shortcut keys Ctrl++ or Ctrl+-. So a good practice is to use em's instead.

    Using px to define the width

    Here is an illustrating example. Say we have a div-tag that we want to turn into a stylish date box, we may have HTML-code that looks like this:

    July

    4

    A simple implementation would defining the width of the date-box class in px:

    * { margin: 0; padding: 0; }
    
    p.month { font-size: 10pt; }
    
    p.day { font-size: 24pt; font-weight: bold; }
    
    div.date-box {
        background-color: #DD2222;
        font-family: Arial, sans-serif;
        color: white;
        width: 50px;
    }
    

    The problem

    However, if we want to size the text up in our browser the design will break. The text will also bleed outside the box which is almost the same what happens with SO's design as flodin points out. This is because the box will remain the same size in width as it is locked to 50px.

    Using em instead

    A smarter way is to define the width in ems instead:

    div.date-box {
        background-color: #DD2222;
        font-family: Arial, sans-serif;
        color: white;
        width: 2.5em;
    }
    
    * { margin: 0; padding: 0; font-size: 10pt; }
    
    // Initial width of date-box = 10 pt x 2.5 em = 25 pt
    // Will also work if you used px instead of pt
    

    That way you have a fluid design on the date-box, i.e. the box will size up together with the text in proportion to the font-size defined for the date-box. In this example, the font-size is defined in * as 10pt and will size up 2.5 times to that font size. So when you're sizing the fonts in the browser, the box will have 2.5 times the size of that font-size.

提交回复
热议问题