CSS - 在div中居中<p>,但文本与左侧对齐

时间:2015-09-10 21:42:17

标签: jquery html css

我在这里看到的答案显示了如何将<p>与中心对齐的文本居中。但是,如何将<p>与左侧对齐的文本居中?我需要它为诗歌网站,所以我不能把我的文字集中在一起。

我希望它看起来像这样:

enter image description here

2 个答案:

答案 0 :(得分:3)

将文本放在容器中(在我的示例中称为poemtext)。这个容器,你使display: inline-block使它成为一个紧贴文本的块,并且可以在父文本中居中。通过一些额外的标记,您可以将诗歌文本居中,并确保它在换行符时自动中断。

请注意,诗歌文本的开头标记的>必须与诗歌的第一行位于同一行,否则您将获得一条额外的白线来引导这首诗。

.poem {
  text-align: center;
}

.poemtext {
  display: inline-block;
  text-align: left;
  white-space: pre-line;
  background-color: #eee;
  padding: 1em;
}
<div class="poem">
  <div class="poemtext"
  > Roses are red
    Violets are blue
    All my base are belong to you
  </div>
</div>

答案 1 :(得分:1)

你在找这个吗?

.my-block {
    border: 1px dotted gray;
}

.my-article {
    margin: 0 20%;
 }

.my-article p {
    text-align: left;
}
<div class="my-block">
    <div class="my-article">
        <p>This is my first paragraph. It is explicitly left-aligned even though the default it inherits from it's parent is the same. It's good to be crystal clear, just in case the parent changes later in the game.</p>
      
        <p>This is paragraph two. The same rules apply. And as you can see these two paragraphs are centered even though there's nothing about centering in the CSS rules!! It's a trick with the margins of the inner div.</p>
    </div>
</div>