将左对齐文本居中

  • 本文关键字:文本 左对齐 html css
  • 更新时间 :
  • 英文 :


我有一些标题文本是大字体,两到四行。 它是左对齐的,但我也希望它水平和垂直居中。 问题是它会在div 的末尾换行并留下一些空白(设置为 600px 的宽度)。 所以我希望它水平居中,不是基于 600px,而是基于最长线的宽度。 有没有办法使div 宽度成为最长文本行的长度?

我想

这就是你想要的吗?

#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>

您可以使用

display: inline-block .内联块元素可以具有宽度,但如果未指定任何宽度,则它们采用其内容的宽度。

尝试将display: inline-block;margin: 0px auto 0px auto;添加到要居中的元素中;我假设您想将不同宽度的div 居中,因此此代码应该有效。

最新更新