What is the best way to center an element vertically and horizontally?

Asked

Viewed 139,957 times

73

What’s the best way (by "better" I mean: with the greatest possible compatibility between browsers and the simplest possible) to position an element in the center of the page, vertically and horizontally and independently of resolution using CSS only?

  • 1

    Semi-duplicate? Horizontally it is easy, vertically see http://answall.com/questions/141/howto center vertically, see vertically

  • 2

    It’s not perfectly clear what you’re asking! There is a universe of ways to center elements on the screen via CSS, but each way is considered an appropriate solution to a specific problem. The way you’re asking the question, there’s no assertive answer.

  • @Zuul who knows is worth giving a general in the forms and their weaknesses and strengths or uses.

  • @Kazzkiq posted an answer answering exactly what you want.

18 answers

89


In my opinion, the best solution is the one that suits many problems. And this is still relative because the problem may be of compatibility or even a fixed height cannot be determined.

PA more compatible solution is not necessarily the best, because compatibility is often only a matter of time. The best solution will depend on the design and how compatible it should be, especially when talking about vertical alignment.

Therefore, I will restrict myself to presenting two great solutions, without determining which is the best.

1. position

Because it is compatible with less modern browsers, perhaps this is the most suitable solution in the overview:

position: absolute;
top: 0; bottom: 0;
left: 0; right: 0;
margin: auto;

2. translateY

position: relative;
top: 50%;
transform: translateY(-50%); 
  • 7

    +1 by the use of the translate that I had never seen used for this purpose. I chose this answer because it has the best support between browsers and still allows the element to be centralized even though it has width and height dynamic, which is very practical.

  • 1

    Genius!! @Diéssica

  • Perfect Brow...

15

Updating the answers, since we have new methods and the compatibility is higher, we can use flexbox, which allows to achieve the result with WELL less code.

See how simple it is:

.classe {
    display: flex;
    align-items: center; //centraliza horizontalmente
    justify-content: center; //cetraliza verticalmente
}

It differs from normal behavior because the flexbox influences the direction in which divs align within it, but you can resolve these layout issues with other properties of the flexbox.

Take this example: https://jsfiddle.net/nhrdd278/

15

There is no better way, it depends on what you are doing, for example if you want to support old browsers it is always better to use old techniques such as tables:

.elemento-principal {
   display: table;
   width: 100%;
}
.elemento-a-ser-centralizado {
   display: table-cell;
   text-align: center;
   vertical-align: middle;
}

But if your target is modern browsers you can use properties that will provide greater control of the elements, for example using flexbox.

Read this tutorial to know how to center elements of any size;
Read this tutorial if you want to know how to use flexbox (all in English).

9

I didn’t see, among the answers, my favorite solution:

HTML

<div class="block">    
    <div class="centered">
    <h1>Some text</h1>
    <p>But he stole up to us again, and suddenly clapping his hand on my shoulder, said&mdash;"Did ye see anything looking like men going towards that ship a while ago?"</p>
</div>  
</div>

CSS

/* This parent can be any width and height */
.block {
  text-align: center;
}

/* The ghost, nudged to maintain perfect centering */
.block:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -0.25em; /* Adjusts for spacing */
}

/* The element to be centered, can
   also be of any width and height */ 
.centered {
  display: inline-block;
  vertical-align: middle;
  width: 300px;
}

Via http://css-tricks.com/centering-in-the-unknown/

I like this solution because using :before the code is clean, I can use the tags that are more semantic to the case and never had problems. The :before works from IE8.

8

For me, it is currently the best form because it allows elements with non-standard height, allowing a greater dynamics.

HTML:

<section>
  <article>
      Centro
  </article>
</section>

CSS:

The align-items vertical alignment and the justify-contentthe horizontal.

section{
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #ddd;
}

article{
  align-items: center;
  display: flex;  
  justify-content: center;
  height: 50%;
  width: 40%;
  background-color: #fff;
}

See that in .article the values of height and width can be changed to either % or pixel.

Demo: https://codepen.io/anon/pen/PZXdzb

  • All browsers support, as long as they are up to date.

  • I don’t understand @Renan. Could you explain to me?

8

As the option using Grid Layout has not been cited in any of the 19 responses, I will leave some instructions on how to do using CSS3 Grid Layout.

Link to the official documentation of Grid Layout module 1 W3C https://www.w3.org/TR/css-grid-1/

Now let’s go to the example:

1 - With display:grid in the Father and margin:auto in the Son

html, body {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
}
.grid > p {
    position: absolute;
}
.grid {
    width: 100%;
    height: 100%;
    display: grid;
    background-color: plum;
}
.centro {
    width: 100px;
    height: 100px;
    background-color: aqua;
    margin: auto;
}
<div class="grid"><p>display: grid;</p>
    <div class="centro">margin: auto;</div>
</div>


2 - With display:grid and place-items:center in the Father, he needs nothing in the Son

html, body {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
}
.grid > p {
    position: absolute;
}
.grid {
    width: 100%;
    height: 100%;
    display: grid;
    place-items: center;
    background-color: plum;
}
.centro {
    width: 100px;
    height: 100px;
    background-color: aqua;
}
<div class="grid"><p>display:grid; place-items:center</p>
    <div class="centro"></div>
</div>


3 - With display:grid and justify-content:center and align-items:center in the Father (similar to Flexbox), does not need anything in the Son

html, body {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
}
.grid > p {
    position: absolute;
}
.grid {
    width: 100%;
    height: 100%;
    display: grid;
    justify-content: center;
    align-items: center; 
    background-color: plum;
}
.centro {
    width: 100px;
    height: 100px;
    background-color: aqua;
}
<div class="grid"><p>display: grid; justify-content: center; align-items: center; </p>
    <div class="centro"></div>
</div>


4 - With display:grid in the Father, and align-self:center and justify-self:center Child (similar to Flexbox)

html, body {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
}
.grid > p {
    position: absolute;
}
.grid {
    width: 100%;
    height: 100%;
    display: grid;
    background-color: plum;
}
.centro {
    width: 100px;
    height: 100px;
    background-color: aqua;
    align-self: center;
    justify-self: center;
}
<div class="grid"><p>display: grid;</p>
    <div class="centro">align-self: center; justify-self: center;</div>
</div>

Browser compatibility of 87.5% in the World and 91% in Brazil according https://caniuse.com/#feat=css-grid * (10/04/2018)

inserir a descrição da imagem aqui

7

The best way, simple and fast. Works 100% of the time, in all browsers.

div {
    width: 200px;
    height: 200px;
    margin-left: -100px; /* metade da largura */
    margin-top: -100px; /* metade da altura */
    position: absolute;
    top: 50%;
    left: 50%;
    border: 1px solid red;
}
  • Including IE6? ;)

  • 11

    IE6 turned back into a browser then? = P

  • There is a country with 2 billion people using ;) pity for those who have to give support. But it’s just curious. http://www.modern.ie/ie6countdown

  • 2

    4.4% of 6 billion people on earth?

6

Using CSS3:

.conteudo-centro{
position: absolute;
z-index: 99999999;
left: 50%; top: 50%;
transform: translate(-50%, -50%);
}
<section class="conteudo-centro">
    <h1>Opa, estamos no centro da tela!<br>
        Independente da resolução do dispositivo do usuário!  ;) </h1>
</section>

Replica in Jsfiddle;

6

If you know the element size (eg 200px 200px), you can perform the alignment as follows:

CSS

#alinhamento{
    top:50%;
    position:absolute;
}

#elemento{
    height:200px;
    width:200px;
    margin:0 auto;
    margin-top:-200px;        
}

HTML

<div id="alinhamento">
    <div id="elemento">
    </div>
</div>

If the element has undetermined height, you should use jquery to detect the size of the element and position it in the center automatically.

5

Horizontally it’s easy to do only through CSS, already vertically the closest you can get is this example, unless Voce uses a little javascript/jquery

div {
    width: 100px;
    height: 100px;
    margin: 25% auto 0;
    border: 1px solid black;
}

5

Just one more suggestion in front of so many;
Use flex box;

.flex-box{
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 400px;

}
<div class="flex-box">
    <div>Conteudo centralizado aqui!</div>
</div>

  • Excellent solution, by the way, currently I believe to be the best use flexbox

1

0

    .container {
        position: absolute;
        width: 100%;
        height: 100%;
        background: #ccc;
    }

    .content {
        position: absolute;
        top: 50%;
        left: 25%;
        width: 50%;
        text-align: center;
        -webkit-transform: translateY( -50% );
        -moz-transform: translateY( -50% );
        transform: translateY( -50% );
    }


<div class="container">
    <div class="content">
        <h1>Valor</h1>
    </div>
</div>
  • Dude, in a question with so many answers already given, it’s hard to verify what you’re bringing back in relation to the other answers, so it’s fair to vote for your answer, whether positively or negatively...

  • Could you summarize the differential of your answer?

  • Kind of "The other answers did not foresee that in situation X it would be much better to do the Y way, as I will present below..."

-1

The best way is using a table. You can turn a DIV or SPAN into a table with CSS: "display: table;" and then align vertically with CSS:"vertical-align: Middle;" I had this doubt too. I went to look at the big sites and saw that Facebook does so. It’s not the most elegant way, but I think the most right.

-1

If you are working with an image <img> can use the vertical-align:middle, but in this case you need to pay attention to the line-height of the element containing the image, it must have the same element size.

*Image-oriented

HTML

<div id="container">
    <img src="http://a.disquscdn.com/next/7b3d8738/assets/img/noavatar92.png" alt="avatar disqus">
</div>

CSS

#container{
    width: 200px;
    height: 200px;
    line-height: 200px;
    text-align: center;
    background: #f00;
}

#container img{
    vertical-align: middle;
}

see for jsfiddle

*Method with knowledge of height

If you have the possibility to define a height for this element can do using the code quoted in an article of Smashing Magazine

HTML

<div>
  magix!
</div>

CSS

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

Javascript solution with jQuery

Now if your focus is another element you can use jQuery, using logic you will leave the distance of your element with 50% of the edges, then control the margin.

see for jsfiddle

  • The solution is with jQuery, and you should make that clear in your answer. Javascript != jQuery.

  • 1

    Thanks Diéssica, I noticed the error but forgot to update :) Inclusive updated to make more usable.

-2

For me one of the best way is to put css

top:50%;
left:50%;

Then put negative margin, half the size of your element

margin-top:-200px
margin-left:-200px

The disadvantage is that the object has to be of fixed size, in this example the object has 400px of height and 400px of width. Remembering that the display should be Absolute.

-3

Just fix a size on the element and give a margin : auto;

div {
   width:200px;
   height:200px;
   margin:auto;
}

-4

As was said there is no "better" way to do this, it all depends on the project.. I usually wear this:

seletor{margin: 0 auto;}

But like I said, it varies a lot from project to project.

  • 2

    This centralizes only horizontally.

  • 1

    Hello André, it is. My mistake! Thanks for the touch...

Browser other questions tagged

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