Center vertically DIV without fixed height in CSS

Asked

Viewed 677 times

1

There are several ways to center the content of a <div> vertically. However, when dealing with a height other than pixels, people begin to wonder if there is an efficient method for this.

I created a way that I found efficient and came here looking for someone who offers a better proposal, because one of the biggest difficulties that a front-end finds today is center a content from a div that does not have pixel height.

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: https://codepen.io/anon/pen/PZXdzb

  • Possibly related : http://answall.com/questions/2817/bestforma-de-centralizar-um-element-vertical-horizontally

2 answers

3

If you are going to consider using flexbox, as in your example, a solution is to use the property align-items:

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

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

  • Great! Thanks for sharing these properties Renan.

  • @Zenojunior But wait for other answers, quiet boy.

  • Ah, I’m starting here. I’ve cleared...

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 easy reading, do not enter the prefixes needed for Transform)

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

Browser other questions tagged

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