Position awareness: absolute

Below is this question of the top answer

Absolute CSS positioning

position: absolute;

This tells the browser that anything that is going to be placed should be removed from the normal flow of the document and placed in the exact place on the page. This will not affect how the elements before or after it in the HTML are positioned on; however, the web page will be affected by the parent's positions if you do not cancel it.

Now look at the following code:

<div class="panel panel-primary">
        <div class="panel-heading">Panel with panel-primary class</div>
        <div class="panel-body">
          <span class="glyphicon glyphicon-circle-arrow-left"></span>
          <img src="../../favicon.ico">
          <img src="../../favicon.ico">
          <img src="../../favicon.ico">
          <img src="../../favicon.ico">
          <img src="../../favicon.ico">
          <img src="../../favicon.ico">
          <span class="glyphicon glyphicon-circle-arrow-right"></span>
        </div>
      </div>

      

if i do: span{ position: absolute;}

this results in the following:

enter image description here

See the position of the arrows, they are positioned relative to the div.panel-header or div.panel-primary , but not relative to the div.panel-body (which is its immediate parent) . I do not understand why?

+3


source to share


3 answers


To quote w3.org CSS2 Specification Section 9.8.4 :

The containing block for a positioned block is set by the closest positioned ancestor

"closest positioned ancestor" is any parent that is not static (default position

)



Edit:

Further reading at MDN , MDN is a great resource for understanding CSS specs, they use a simpler language than the official specs.

+2


source


absolute

: This removes the element, including any child elements, completely from the document flow, and positions it at the specified offsets. If an element is nested within another positioned element, offsets are calculated with reference to the positioned parent. Otherwise, offsets are calculated with reference to the page.



set position: relative to parent and see the result.

+1


source


Try to avoid absolute positioning whenever you can. The layout you probably need can be easily achieved with flexbox.

.panel-body {
  display: flex;
  justify-content: space-around;
  align-items: center;
}
      

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="panel-body">
  <span class="glyphicon glyphicon-circle-arrow-left"></span>
  <img src="http://placehold.it/50">
  <img src="http://placehold.it/50">
  <img src="http://placehold.it/50">
  <img src="http://placehold.it/50">
  <img src="http://placehold.it/50">
  <img src="http://placehold.it/50">
  <span class="glyphicon glyphicon-circle-arrow-right"></span>
</div>
      

Run codeHide result


0


source







All Articles