How to center the text of a div in Javascript?

Asked

Viewed 840 times

-3

I’m starting now with JS, I created a div and wanted the text inside it to always be in the center of the box. How can I do that?

What I have so far :

div#CaixaPrincipal{
            
            background: white;
            width: 600px;
            height: 300px;
            margin : 0 auto 0 auto;
            align-items : center;
            font : normal 15pt Arial;
            
        }

  • Actually the line "align-items" doesn’t exist, I was testing to see if it lined up but it didn’t work :/

  • This is not Javascript, it’s CSS.

  • But this code is CSS friend, not JS rs'

  • Just add display: flex; and justify-content: center;. That takes care of.

  • Without seeing your HTML not to answer you, most likely you are using the wrong property, since your container has no flex, a simple text-align: center; must solve

1 answer

0

You were right to use the align-items: center, but to use it you need the display: flex; too! Then just do the following:

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

This will center all page content.

If you want to keep the default HTML distribution, you can direct to list the code by columns:

div {
     display: flex;
     flex-direction: column;
     justify-content: center;
     align-items: center;
}

If you want to know more about the flexbox I will leave this link in PT that talks more on the subject: https://origamid.com/projetos/flexbox-guia-completo/

I hope it helped, hugs!

  • This centralizes only horizontally. As he clearly says in the question he wants to center, he would have to center vertically as well.

  • I voted against because your answer does not help much. It only centralizes horizontally. And why use flex-direction: column;? If you improve the answer I’ll change the vote.

  • @Sam sorry for the mistake, I’ve changed the answer.

Browser other questions tagged

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