How to center text in the DIV making the lines line up on the left?

Asked

Viewed 28 times

2

I have a <div> with the property text-align: center; so that the text is centralized, but I want the lines of the texts to always start on the left.

Below is an example of what I want:

             <DIV>               
-----------------------------
|                           |
|      Olá pessoal          |
|      Este é um exemplo.   |
|      Do que eu quero.     |
|                           |
-----------------------------

How can I do that? Is it possible? The code I’m using is this:

#myDiv {
    text-align: center;
}
<div id="myDiv">
    <!-- Alguns outros elementos... -->
    <div id="info">
        Dado 1: 334<br>Dado 2: 192.2<br>Dado 3: 3455.234
    </div>
</div>

1 answer

4


You can simply create a sub-element that is display: inline-block;, the element with inline-block will not occupy "100%", do not specify measure, just let the text adjust it, then it should look like this:

#myDiv {
    text-align: center;
}

#info {
    text-align: left;
    display: inline-block;
}
<div id="myDiv">
    <!-- Alguns outros elementos... -->
    <div id="info">
        Dado 1: 334<br>Dado 2: 192.2<br>Dado 3: 3455.234
    </div>
</div>

If you’re really going to use other elements before the #info you can use a simple <br> to separate:

#myDiv {
    text-align: center;
}

#info {
    text-align: left;
    display: inline-block;
}
<div id="myDiv">
    <!-- Alguns outros elementos... -->
    <p>foo</p>
    <p>bar</p>
    <p>baz</p>

    <br>

    <div id="info">
        Dado 1: 334<br>Dado 2: 192.2<br>Dado 3: 3455.234
    </div>
</div>

Or you can create a "sub-div" inside #info and apply to it the display: inline-block; instead of applying on #info

  • @Luizfelipe yes, I must point out that using flex for something as trivial as this is like hiring a hydraulic engineer to discharge your discharge for you. Flex and grid are things that have a number of characteristics, including affecting the parent element, which is another problem, you have to understand the behavior of the box-model (https://www.w3.org/TR/css-box-3/) which is something that if we lose can complicate quite a lot in a failure difficult to detect, should a failure occur.

  • I must agree. :-)

Browser other questions tagged

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