Centralize DIV vertically with no fixed height in CSS

1

There are several ways to centralize the content of a <div> vertically. However, when it comes to a height other than in pixels, people are beginning to wonder if there is an efficient method for doing this.

I created a form that I found to be efficient and came here looking for someone who offers a better proposal, since one of the biggest difficulties that a front end finds today is centering a content of a div that does not have height in pixels .

HTML:

<section>
  <article>
    <div>
      <p>Centro</p>
    </div>
  </article>
</section>

CSS:

section{
  position: relative;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #ddd;
  display: flex;
  flex-direction: column;
}

article{
  flex: 1;
  display: flex;
  margin: 0 auto;
}

article > div{
  margin: auto 0;
}
  

Demo: link

    
asked by anonymous 11.02.2016 / 16:28

2 answers

3

If you are considering using flexbox, as in your example, one solution is to use the align-items :

html, body {
  margin: 0;
  height: 100%;
  width:  100%
}

body {
  align-items: center;
  display: flex;  
  justify-content: center
}
<div>olá</div>
    
11.02.2016 / 16:40
1

A good alternative is:

section{
   position: relative;
   width: 100%;
   height: 100%;
}
article > div{
   position: absolute;
   top: 50%;
   left: 50%;
   transform: translate(-50%, -50%);
}

(for ease of reading, I did not enter the prefixes needed for the transform)

Using this method, I usually set a maximum width for div .

    
11.02.2016 / 16:39