user3407039
user3407039

Reputation: 1335

CSS centre text on multiple lines

I need to apply some text within a div horizontally and vertically, which was working fine with this solution that has been posted on stack overflow before -

text-align: center;
vertical-align: middle;
line-height: 90px;   

/* the same as your div height */

My issue is that I have multiple lines and I am wrapping the words onto a new line with -

white-space: normal;

My text is within a button so i need this line to counteract the btn class that will not allow for text to wrap normally.

However when I do this there will now be a huge gap inbetween my lines of 90px, as you'd expect. Is there a way to get around this? Or another way to centre my text?

Upvotes: 2

Views: 1721

Answers (3)

Paulie_D
Paulie_D

Reputation: 114991

CSS tables work quite well

div {
  height: 250px;
  border: 1px solid #000;
  display: table;
}
p {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}
<div>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer at efficitur nulla. Suspendisse potenti. Ut viverra velit in lobortis euismod. Mauris cursus mollis porta. Praesent ullamcorper imperdiet placerat. Nam sit amet aliquam leo. Ut a facilisis
    ex, ut fermentum felis</p>
</div>

Upvotes: 4

Adam Jenkins
Adam Jenkins

Reputation: 55613

Sans flexbox approach:

Give your container element a line-height equal to it's known height and then give a child element that contains the text a line-height of 1 (or whatever is desirable). Make sure to set the child to display: inline-block

div { height: 250px; line-height: 250px; border: 1px solid #000;}
span { line-height:1; display: inline-block;}
<div>
    <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer at efficitur nulla. Suspendisse potenti. Ut viverra velit in lobortis euismod. Mauris cursus mollis porta. Praesent ullamcorper imperdiet placerat. Nam sit amet aliquam leo. Ut a facilisis ex, ut fermentum felis</span>
</div>

Upvotes: 2

passatgt
passatgt

Reputation: 4432

Use flexbox:

<div id="container">
<div class="content">Multi line content centered both vertically and horizontally. You can use block elements & images too.</div>
</div>

Css is simple:

#container {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-webkit-align-items: center;
-ms-flex-align: center;
align-items: center;
height: 90px;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
}

More info: http://philipwalton.github.io/solved-by-flexbox/demos/vertical-centering/

Upvotes: 0

Related Questions