2015-09-04 31 views
0

我有一些文本需要對齊到左側,但保持相同的行格式,就好像它居中。這是一個例子。如何讓文本左對齊但格式化,就好像它居中

<!DOCTYPE html> 
<html> 
<body> 

<p>This is some text.</p> 
<center>this text is line number one. 
<br>this is line 2 
<br>this is line number three</center> 
<p>This is some text.</p> 


</body> 
</html> 

此代碼爲您提供了這樣的輸出:

This is some text. 

          this text is line number one. 
            this is line 2 
           this is line number three 
This is some text. 

我想是居中左對齊文本,但保留原來的格式。即:第一行長,第二行短並居中在第一行下,並且第一行的第一個字母一路向左。對不起,如果這沒有意義。我不知道如何解釋它。

+1

請不要使用'

'[anymore](http://www.w3schools.com/tags/tag_center.asp)。 – D4V1D

回答

2

您可以浮動的段落到與text-align:center;左沿,然後使用clearfix這樣的:

p.center-left { 
 
    text-align:center; 
 
    float:left; 
 
} 
 

 
.clearfix:before, 
 
.clearfix:after { 
 
    content: " "; 
 
    display: table; 
 
} 
 
.clearfix:after { 
 
    clear: both; 
 
}
<p>This is some text.</p> 
 
<p class="center-left">this text is line number one. 
 
<br>this is line 2 
 
<br>this is line number three</p> 
 
<div class="clearfix"></div> 
 
<p>This is some text.</p>

+0

謝謝,這工作。 – Andrew

0

我不是100%肯定你的意思,但告訴我如果這是你想要的結果?

HTML:

<body> 

<p>This is some text.</p> 
<div class="center">this text is line number one. 
<br>this is line 2 
<br>this is line number three</div> 
<p>This is some text.</p> 


</body> 

CSS:

.center 
{ 
    width: 50%; 
    margin:auto; 
} 

小提琴:

https://jsfiddle.net/u2geno6u/

0

div.centered { 
 
    border: 1px solid red; 
 
    text-align: center; 
 
    display: inline-block; 
 
}
<!DOCTYPE html> 
 
<html> 
 
<body> 
 

 
<div> 
 
    <p>This is some text.</p> 
 
     <div class="centered"> 
 
      this text is line number one. 
 
      <br>this is line 2 
 
      <br>this is line number three 
 
     </div> 
 
    <p>This is some text.</p> 
 
</div> 
 

 
</body> 
 
</html>

-2

把你的文字與顯示一個div:inline-block的,然後將文本居中

Here is a codepen

HTML:

<!DOCTYPE html> 
<html> 
    <body> 
     <div style="display: inline-block"> 
      <p>This is some text.</p> 
      <p>this text is line number one.</p> 
      <p style="text-align: center">this is line 2</p> 
      <p style="text-align: center">this is line number three</p> 
      <p>This is some text.</p> 
     </div> 
    </body> 
</html> 
2

.centered { 
 
    text-align : center; 
 
    display : inline-block; 
 
} 
 

 
.left-aligned { 
 
    /* no need to float : left in this case */ 
 
}
<p>This is some text.</p> 
 
<div class="left-aligned"> 
 
    <div class="centered"> 
 
     <div>this text is line number one.</div> 
 
     <div>this is line 2</div> 
 
     <div>this is line number three</div> 
 
    </div> 
 
</div> 
 
<p>This is some text.</p>

我使用了兩個<div> ,使父項對齊到左側(不需要css屬性float : left),並且子項將具有兩個屬性,一個用於居中內容text-align : center,並與display : inline-block合併,則您擁有最小的div可能因爲inline-block屬性而在寬度上。

相關問題