skip to Main Content

I created a small test web page, and the line heights are different, although they use the same CSS style. This becomes most visible when using Chrome to highlight the usage of the .instruction class. It seems as if the total margins between two lines are cut in half for items directly right to the bracket.

The CSS file is available here.

Keeping in mind that all lines use the exact same .instruction class CSS style:

.instruction {
    max-width: 48ch;
    display: flex;
    flex-direction: row;
    margin: 0.2em 0em;
    vertical-align: middle;
}

Any help would be greatly appreciated!

enter image description here

2

Answers


  1. There might be 2 reasons why it is happening:

    Reason 1

    em unit is relative to the font size of the parent element. link

    Your margin size is differing because the font size of the parent element is different.

    If you want to use consistent margin, either use absolute values such as margin: 5px 0; or relative unit rem.

    rem is relative to the font size of the the root element, (default 16px).

    .instruction {
        max-width: 48ch;
        display: flex;
        margin: 0.2rem 0;
        vertical-align: middle;
    }
    

    Reason 2

    Margin Collapsing

    The top and bottom margins of blocks are sometimes combined (collapsed) into a single margin whose size is the largest of the individual margins (or just one of them, if they are equal).

    You can read more about margin collapsing and when it happens on this page.

    How to prevent margin collapsing?

    One easy hack is to use display:flex; or display:grid;.

    Margins don’t collapse in a container with display set to flex or grid.



    SideNote:

    flex-direction: row; is a default value, so you don’t have to define it. link

    Login or Signup to reply.
  2. Try using px or rem while giving margins.

    .instruction {
    max-width: 48ch;
    display: flex;
    margin: 0.2rem 0;
    vertical-align: middle;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search