2016-10-11 102 views
2

我需要設置一首包含左對齊,右對齊和完全對齊線條的詩。有沒有辦法將容器的寬度設置爲匹配特定(最長)的行而不是猜測?根據線條長度設置容器的寬度

下面是一個演示Word中佈局的樣機模型(注意「這是測量截面的線條」,它決定了文本出現的方框的大小)。

enter image description here

我怎樣才能做到這一點的佈局,CSS?

回答

1

您可以在<div>之內嵌套段落以達到您要查找的效果。包含<div>的外部應該使用display: inline-block來設置其子級設置的寬度。

在示例代碼段中,中間一行是可編輯的。您可以添加或刪除角色看到容器的拉伸和收縮,以匹配:

.container { 
 
    border: solid; 
 
    display: inline-block; 
 
} 
 
.right-aligned { 
 
    text-align: right; 
 
}
<div class="container"> 
 
    <p>left aligned</p> 
 
    <p contenteditable="true">a full width line that sets the width of the container</p> 
 
    <p class="right-aligned">right aligned</p> 
 
</div>

爲了得到一個合理的線伸展盒子的全寬,你必須實現一些僞元素詭計,還有另一個解決方案here

在你的情況下,你添加一個:after僞元素到你合理的類,並以它在你的段落內創建一個新行的方式來設置它。這應該強制文本的行爲像一個段落,並證明左右兩側。

要擺脫空行,你可以只設置一個高度上的兩端對齊的段落:

.container { 
 
    border: solid; 
 
    display: inline-block; 
 
} 
 
p { 
 
    border: 1px dotted red; 
 
} 
 
.right-aligned { 
 
    text-align: right; 
 
} 
 
.justified { 
 
    text-align: justify; 
 
} 
 
.justified:after { 
 
    content: ""; 
 
    display: inline-block; 
 
    width: 100%; 
 
} 
 
.no-space { 
 
    height: 1.2em; 
 
}
<div class="container"> 
 
    <p>left aligned</p> 
 
    <p contenteditable="true">a full width line that sets the width of the container</p> 
 
    <p class="right-aligned">right aligned</p> 
 
    <p class="justified">justified text with blank line</p> 
 
    <p class="justified no-space">justified text without the following blank line</p> 
 
</div>

+0

這讓我最的方式,但完全有理由線(如一個開始「培根和培根」)沒有伸展。請參閱:https://jsfiddle.net/vLq0yt7h/1/ – Chris

+0

@Chris我添加了關於從頭到尾拉伸線的另一個片段。我想我找到了一個相當可行的解決方案。 – worc

相關問題