Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

margin-top in percentage not working as expected

Tags:

html

css

margin

I know what you're thinking, but the parent container(s) are all positioned with pixels.

I have a div with a height and width in pixels, inside that div I have a youtube iframe that has (for this example) it's margin-top in percentage.

This the HTML:

Elements console

And this is the result:

enter image description here

I know it's a ridiculously small frame (right bottom of selected div) but it's just an example :)

As you can see, in code I have the margin-top set to 99% but it's actually positioned a lot lower. What could be the cause of this?

like image 519
DerpyNerd Avatar asked Dec 06 '22 02:12

DerpyNerd


2 Answers

The point is that a percentage value for top/bottom margin/padding properties is relative to the width of the box's containing block. It doesn't respect the height of the parent element.

8.3 Margin properties: 'margin-top', 'margin-right', 'margin-bottom', 'margin-left', and 'margin'

<percentage> The percentage is calculated with respect to the width of the generated box's containing block. Note that this is true for margin-top and margin-bottom as well. If the containing block's width depends on this element, then the resulting layout is undefined in CSS 2.1.

As you are using absolute positioning, try using top: 99% instead in which a percentage value refers to the height of the box's containing block.

like image 51
Hashem Qolami Avatar answered Dec 08 '22 17:12

Hashem Qolami


A percentage based margin-top value won't work because it is calculated from the width of the containing element, as previously stated.

If you need a fluid, responsive, scalable margin based on width and can't use absolute positioning try using viewport units in your CSS. Viewport units behave very similarly to percentage based dimensions except that they are calculated from the dimensions of your viewport window and will scale and resize according to the dimensions of your browser window.

vw = Viewport Width: This measurement is based on the width of the viewport. A value of 1vw equals 1% of the viewport width.

vh = Viewport Height: This measurement is based on the height of the viewport. A value of 1vh equals 1% of the viewport height.

You can use decimals of percentages also, like so-

.container {
    margin-top: .3vw;
}

Viewport units were not that widely supported a few years ago, but all modern browsers support them now. If you familiarize yourself with them it will open up a lot more options for you.

like image 44
David Glusenco Avatar answered Dec 08 '22 17:12

David Glusenco