Margin in percent is relative to what?

7

I'm currently seeing a video on youtube on how to create a responsive website . He, at a certain point (minute 24.55), sets the margin of an image in percent rather than using the normal pixels. What I do not understand is what width or length the percentage is relative, ie these 2% are in relation to what width? And 0 is exactly what? (I have a certain intuition, but with the CSS the intuitions, honestly, serve little.)

.mainheader img{
    width:30%;
    height:auto; /* automatically determines the height*/
    margin: 2% 0;
}

In general, the percentages are in relation to what?

    
asked by anonymous 11.10.2014 / 12:51

3 answers

6

The percentage value is relative to the upper block (in this case the block containing the element in question).

In your case, the margin of the images inside an element of class .mainheader will be in 2% of the top and the "footer".

Example:

In the next image we have the upper element defined with 900px fixed width, and a child element that has as its width ( width ) 50% of the upper element (which would correspond to 450px).

The%w/w%thatcomesafterthevaluedefinedinpercentageisusedtodefinethemargingiveninrelationtothetopandthebottom(bottom). Here you can see better.

Here are the ways to define the margin (I used 0 plus it could be another unit):

.elementoTeste { margin: 2px }         /* all margins set to 2px */
.elementoTeste { margin: 1px 2px }     /* top & bottom = 1px, right & left = 2px */
.elementoTeste { margin: 1px 2px 3px } /* top=1px, right=2px, bottom=3px, left=2px */
    
11.10.2014 / 17:54
6

It is relative to the upper block length.

#yellow {
  width: 300px;
  height: 100px;
  background-color: yellow;
  border-bottom: 2px solid black;
}
.red {
  width: 50%;
  height: 25px;
  background-color: red;
  border-bottom: 1px solid black;
}
.green {
  width: 50%;
  height: 50%;
  background-color: green;
  margin-left: 50%;
}
.blue {
  background-color: blue;
  height: 50%;
  margin-left: auto;
  margin-right: auto;
  width: 40%;
}
<div id="yellow">
  <div>
    <div class="red"></div>
    <div class="red">
      <div class="green"></div>
    </div>
  </div>
  <div class="blue"></div>
</div>
<div id="white">
  <div>
    <div class="red"></div>
    <div class="red">
      <div class="green"></div>
    </div>
  </div>
  <div class="blue"></div>
</div>
    
11.10.2014 / 13:13
1

In the specified case it would be relative to 100% of the ".mainheader", ie the img would be 2% away at the top and 100% of the mainheader footer

    
11.10.2014 / 13:06