Pan.J
Pan.J

Reputation: 13

How to center a div but left align text inside?

I want to put a div block in the center of a page, but the text should stay left of the centered block.

The problem is when I set the div to center and p to left, the content inside p is on the left of entire page not the left of centered block.

.container {
  text-align: center;
  margin: auto;
}

.container p {
  text-align: left;
}
<div class="container">
  <p>The quick brown fox jumps over the lazy dog.</p>
</div>

Upvotes: 0

Views: 347

Answers (3)

Stickers
Stickers

Reputation: 78796

In your example, margin: auto; or margin: 0 auto; is the correct approach, however div is block level element, and it occupies the entire available width by default, so the margin: auto; has no effects visually.

All you need is to declare the width or max-width that is either percentage or fixed, as long as it's smaller than the parent element.

.container {
  margin: 0 auto;
  max-width: 200px;
  border: 1px solid;
}
<div class="container">
  <p>The quick brown fox jumps over the lazy dog.</p>
</div>

Additionally, You can do it with display: table; because it has the shrink-to-fit feature. This works even without any width being set there.

.container {
  display: table;
  margin: 0 auto;
  border: 1px solid;
}
<div class="container">
  <p>The quick brown fox jumps over the lazy dog.</p>
</div>

<div class="container" style="max-width: 500px;">
  <h2>Example: max-width and wrapping text</h2>
  <p>The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.</p>
</div>

Or, display: inline-block; similar feature as above. Note, an additional wrapper is required if you don't want to target the body tag.

.outer {
  text-align: center;
}

.container {
  border: 1px solid;
  display: inline-block;
  text-align: left;
}
<div class="outer">
  <div class="container">
    <p>The quick brown fox jumps over the lazy dog.</p>
  </div>
</div>

Upvotes: 1

Mahesh C. Regmi
Mahesh C. Regmi

Reputation: 81

Do you mean at the center of the page ? Else you can do like this

div.container {
   text-align: center;
   max-width : 700px;
   margin : auto;
   background : blue;
   }

p {
    text-align: left;
}

Upvotes: 0

Rahul Dev
Rahul Dev

Reputation: 175

By default, the text is always left. And you should give width to the container or it will be of full size as of the page.

.container {
  width: 1000px;
  height: 500px;
  margin: auto;
  border: 1px solid red;
}

<div class="container">
  <div class="another-container">
    <p>Some text goes here.</p>
  </div>
</div>

Upvotes: 0

Related Questions