Centering using the Absolute position

Asked

Viewed 11,209 times

5

I don’t understand the following code:

div{
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    width: 100px;
    height: 100px;
    background: red;
}

Online example

I know that set top: 0 and bottom: 0 and set a width the element will stretch occupying height: 100% of the parent element(body), the same with left: 0 and right: 0 (correct me if I’m wrong). But what I don’t understand is the margin: self, someone can explain to me how it will center the element in the center ?

3 answers

3

To center something in the center of the page there are several techniques.

Explaining the margin its function as observed is to define a margin for some element, and when its value is auto means that the browser will set the margin automatically, follows example:

.quadrado{
  background-color: red;
  display: block;
  height: 100px;
  margin: 0 auto;
  width: 100px;
}
<div class="quadrado"></div>

Note that I am using margin: 0 auto zero represents the margin-top and the margin-bottom, and the value auto represents the margin-left and the margin-right summarizing is an abbreviation.

In my example the right and left margins are automatic and with this the browser automatically sets its positioning, and when the element is a block with defined width it centralizes horizontally.

To align horizontally and vertically I would use this technique:

body, .container, html{
  height: 100%;
}

.container{
  display: flex;
  align-items: center;
  justify-content: center;
}

.quadrado{
  background-color: red;
  display: inline-block;
  height: 100px;
  width: 100px;
}
<div class="container">
   <div class="quadrado"></div>
 </div>

obs. When you set margin: auto you are assigning an automatic margin to top right bottom left

0

div{
    position: absolute;
    left: 50%;
    margin-left: -50px;
    width: 100px;
    height: 100px;
    background: red;
}

This snippet of code should solve your problem.

-1

Hello, I was with this doubt too and put in the div with absolute the left and the right with -50%

div{
    position: absolute;
    top: 0;
    left: -50%;
    right: -50%;
    width: 100px;
    height: 100px;
    background: red;
}

In my case, I didn’t put the bottom: 0;, but it may be that in your case it is necessary.

  • With this code the div does not even appear on the screen, you tested it where? https://jsfiddle.net/twhxf5k4/ does not work

Browser other questions tagged

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