How to calculate percentage in top css property?

Asked

Viewed 519 times

0

I wanted to know how to calculate percentage in the top property. I searched in Google, but I did not find to my doubt.

  • Simple... - top:10%;

  • I wanted to know how to calculate if it equals the margin properties ?

  • 2

    If you ask broad questions, broad answers will appear. Edith your question and add more information and explain in detail what your goal or problem is.

1 answer

1


First of all, a clarification, I imagine you already know, but emphasizing, the property top will only work with enlightenment of property position, and that choice must be well made, as you can see.

The percentage will actually make a percentage calculation according to the size of the "parent element", however, it will vary according to some factors, such as:

The hierarchy of elements

The property position: relative

If you wanted to use the percentage on a loose page element, which is not a "child" of any other element, the percentage will refer to the "father of all", the body, in other words, the size of the window itself.

But if this belongs to another element, it will follow the same logic, it will relate to the size of this parent. Example:

#filho{
  width: 50px;
  height: 50px;
  background: #333333;
  position: relative;
  top: 50%;
}
#pai{
  width: 300px;
  height: 300px;
  background: #f09
  }
<div id="pai">
  <div id="filho"></div>
</div>
As you can see, he was 50% relative to the upper edge of the child element.

However, there is a certain malleability when using the position: relative, because the position will be relative :) to the existence of other elements. Example:

#filho1{
  width: 50px;
  height: 50px;
  background: #333333;
  position: relative;
  top: 50%;
}
#filho2{
  width: 50px;
  height: 50px;
  background: #cccccc;
  position: relative;
  top: 50%;
}
#pai{
  width: 300px;
  height: 300px;
  background: #f09;
  position: absolute;
  }
<div id="pai">
  <div id="filho1"></div>
  <div id="filho2"></div>
</div>

How can one perceive a chaining. In the example, the filho1 "moved away" the filho2. What will not be contained in position: absolute.

The position: Absolute

The chaining will not happen in this case the children will overlap, they do not take into account the existence of each other:

#filho1{
  width: 50px;
  height: 50px;
  background: #333333;
  opacity: 0.5;
  position: absolute;
  top: 50%;
}
#filho2{
  width: 50px;
  height: 50px;
  background: #cccccc;
  opacity: 0.5;
  position: absolute;
  top: 50%;
}
#pai{
  width: 300px;
  height: 300px;
  background: #f09;
  position: absolute;
  }
<div id="pai">
  <div id="filho1"></div>
  <div id="filho2"></div>
</div>

Is that what you wanted to know? If so, I hope you understood, and any doubt...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.