1

What is the problem?

I am trying to align two boxes within divs to be on the same level as one another, whilst covering the whole page. The div widths should be 40% for the left and 60% for the right. And then the height/width of the divs inside should be height: 100%; and width: 90%;.

CSS is adding extra margin to the right div, therefore making the div's unevenly aligned from the top.

See the two examples below:

Not working codepen - Unevenly aligned with correct widths.

Aligned codepen - Evenly aligned with incorrect widths.

As you can see, the only change from the two codepen examples is that the width of the TicketMainRight div has been changed from width: 60%; to width: 40%;. This now leaves me 20% free, which I don't want. I want to keep the 60% width without the margin being increased from the top.

Why is CSS adding more than 2.5% margin from the top when only the width is increased?

Jonathan Davies
  • 882
  • 3
  • 12
  • 27

3 Answers3

3

It's not "adding more than 2.5%", it's giving margin of 2.5% of the width.

Margin percentage is calculated against the width of the element. As for why, see this answer.

Community
  • 1
  • 1
Lazar Ljubenović
  • 18,976
  • 10
  • 56
  • 91
  • Thanks for the prompt response. I understand that the `margin-left: 2.5%;` would be affected as I am changing the width, but I don't get why `margin-top` is being affected because I am not altering the height? @Lazar – Jonathan Davies Sep 01 '16 at 13:25
  • 1
    All margins are calculated against the **width** of the element, both `left` and `top`. Check the linked question and its answers for why CSS is modeled this way. – Lazar Ljubenović Sep 01 '16 at 13:26
2
margin-left: 2.5%;

and

margin-top: 2.5%;

are relative to the parent's width. So 2.5% of 40% is smaller margin than 2.5% of 60%. You could use em.

dVeza
  • 557
  • 4
  • 12
1

Percentage margin and padding values are relative to the parent elements width.
Additionally margin and padding add up to the dimensions of your element (see box model). So if you have a width of 100% and 2.5% margin it will be 102.5% width. If you dont want the margin to increase while the width increases you should use a fixed margin.

Code Spirit
  • 3,992
  • 4
  • 23
  • 34