The Hawk February 2016

Center a Div Left Justified Text

I have some header text that is large font, two to four lines. It is left justified, but I also want it centered horizontally and vertically. The problem is that it wraps and leaves some blank space at the end of the div (which is set at a width of 600px). So I want it to be centered horizontally, based not on 600px, but the width of the longest line. Is there a way to make the div width the length of the longest line of text?

Answers


GMchris February 2016

You can use display: inline-block. Inline-block elements can have a width, but if none is specified, they take the width of their content.


Syd Lambert February 2016

Try adding display: inline-block; and margin: 0px auto 0px auto; to the element you want to centre; I am assuming that you want to centre a div of a varying width, so this code should work.


freestock.tk February 2016

I guess that's what you want?

#container {
  background:gold;
  width:600px;
  font-size:2em;
  display:inline-block;
  }

#title {
  width:400px;
  margin-right:100px;
  margin-left:100px;
  margin-top:50px;
  margin-bottom:50px;
  font-weight:600;
  }
<html>
<head></head>
<body>
  
<div id=container>
<p id=title>Here it comes a long sentence that takes about 2 lines.</p>
</div>
  
</body>
</html>

Post Status

Asked in February 2016
Viewed 3,235 times
Voted 6
Answered 3 times

Search




Leave an answer