nrojina0
nrojina0

Reputation: 243

How do I have left-aligned text in the center of a div?

I was wondering if anybody knows how to center text that is left aligned. Here's an example of what I mean:

This text
is
left aligned.

                                  This text
                                  is
                                  left aligned
                                  and in
                                  the center (isn).

How can I do that inside a div? I've tried the one answer I've seen everywhere which is to put text-align:center in a parent div and then in the child div put text-align: left, but this does not seem to work. Here is an example: http://codepen.io/nrojina0/pen/OXGdXJ

div#stores {
  font-size: 1.25em;
  width: 100%;
  text-align: center;
  border: 1px solid black;
}
div#storesleft {
  display: inline-block;
  float: left;
  width: 33%;
  text-align: left;
  margin: 0 auto;
  border: 1px solid black;
}
<div id="stores">

  <div id="storesleft">

    Boo and Roo's
    <br>112 E. Moore St.
    <br>Southport, NC 28461
    <br>(910)363-4275
    <br>
  </div>

</div>

Upvotes: 1

Views: 49

Answers (1)

Paulie_D
Paulie_D

Reputation: 115374

I was wondering if anybody knows how to center text that is left aligned.

Just remove the float from the "centered" child..

"The first rule of centering is...don't use float!"

div#stores {
  font-size: 1.25em;
  width: 100%;
  text-align: center;
  padding: 1em;
}
div#storesleft {
  display: inline-block;
  width: 33%;
  text-align: left;
  margin: 0 auto;
}
<div id="stores">

  <div id="storesleft">

    Boo and Roo's
    <br>112 E. Moore St.
    <br>Southport, NC 28461
    <br>(910)363-4275
    <br>
  </div>

</div>

I want the text in each of the three child divs to be left aligned, but still in the center of their div. How would I do that?

From your amended requirements (in the comments) I'd use flexbox to avoid have to add additional wrappers.

Demo with required additional wrappers : Codepen Demo

Flexbox Demo:

div#stores {
  font-size: .85em;
  width: 100%;
  display: flex;
  justify-content: space-around;
}
div#storesleft {
  border: 1px solid black;
}
div#storescenter {
  border: 1px solid black;
}
div#storesright {
  border: 1px solid black;
}
<div id="stores">

  <div id="storesleft">

    Boo and Roo's
    <br>112 E. Moore St.
    <br>Southport, NC 28461
    <br>(910)363-4275
    <br>
  </div>

  <div id="storescenter">

    Natural Food Store
    <br>1920 U.S. Hwy 70 SW
    <br>Hickory, NC 28602
    <br>(828)322-5316
    <br>
  </div>

  <div id="storesright">

    Routh's Grocery
    <br>3796 Chatham Street
    <br>Bennett, NC 27208
    <br>(336)581-3465
    <br>

  </div>

</div>

Upvotes: 3

Related Questions