John
John

Reputation: 13757

Horizontally and Vertically Center Paragraph text Simultaneously

I need to horizontally and vertically center text in a paragraph. The paragraph itself must fill 100% of the available height and width of the parent element without setting an explicit/static width for the paragraph (percentage like 100% is acceptable).

HTML

<div>
<p>Sudo make me a sandwich.</p>
</div>

CSS

div
{
 background-image: url('idahoisntafraidofgorillas.png');
 height: 138px;
 width: 100%;
}

p
{
 display: table-cell;
 text-align: center;
 vertical-align: center;
}

Ideally this should not require anything greater than CSS level 2. The current code doesn't actually center the text unless I set a static width however that would spam up the CSS I'm working on so I'm seeking a more elegant and proper solution.

Upvotes: 2

Views: 165

Answers (2)

Wowsk
Wowsk

Reputation: 3675

Set the line-height, vertical-align:middle;, and make sure there is no extra margin, margin:0px; all on the paragraph element.

div {
 height: 138px;
 width: 100%;
 border: 1px solid black;
}

p {
  margin:0px;
  line-height:138px;
 text-align: center;
 vertical-align: middle;
}
<div>
  <p>Sudo make me a sandwich.</p>
</div>

Upvotes: 2

Nenad Vracar
Nenad Vracar

Reputation: 122087

Try vertical-align: middle also add display: table to div

div {
 height: 138px;
 width: 100%;
 border: 1px solid black;
 display: table;
}

p {
 display: table-cell;
 text-align: center;
 vertical-align: middle;
}
<div>
  <p>Sudo make me a sandwich.</p>
</div>

Upvotes: 2

Related Questions