2017-03-10 52 views
1

我試圖在父元素太長的情況下將元文本內部的文本放入。該跨度具有:在具有固定寬度的僞元素之前。CSS在僞元素太大之前進行文本換行

問題是,當我將white-space: normal添加到父元素時,span文本會換行到下一行,但會一直移動到父元素的左側......這很難用單詞解釋,所以這裏有一個的jsfiddle:

https://jsfiddle.net/cpkzwzko/1/

我想跨度文字換行,但第包裹字以上行的第一個字是內聯,如本嫺熟的樣機展示。

enter image description here

enter image description here

我嘗試添加white-space: nowrap;父元素和white-space: normal;的跨度,但它不工作。

這是可能使用CSS?

謝謝大家!

感謝任何

回答

2

首先,你會希望一個元素爲inline-block的,而不是一個內聯,因爲你不希望它的內容流的普通文字。我會用div替換span以保持語義準確。然後,您希望它獲得其母公司的50%,就像之前一樣。

50%+ 50%+一對像素的邊框太大而不適合父元素,所以第二個內嵌塊會換行。爲了防止出現這種情況,請使用使CSS屬性包含邊框和填充的邊框。此代碼將應用於網站上的所有元素,這正是許多現代網站所做的,因爲它使CSS更簡單。

*, *:before, *:after { 
    box-sizing: inherit; 
} 
html { 
    box-sizing: border-box; 
} 

與內聯塊元件的問題是,一個單一的空間被保持在它們之間,因此,即使在50%的兩個元件,一個空間將存在於兩者之間。爲了防止...你必須刪除HTML代碼中的空間。

<div class="parent"><div> 
    This is a string which is too long to fit in the parent next to it's :before pseudo selector 
</div></div> 

所以,不要在父母和子div之間放置換行符或任何空格。這是一種恥辱,但我們無法做的其他事情。除此之外,這也適用:

<div class="parent"><!-- 
    --><div> 
    This is a string which is too long to fit in the parent next to it's :before pseudo selector 
    </div><!-- 
--></div> 

但它是相當醜陋的。

現在您還需要在您的元素上放置垂直對齊,以便它們對齊頂部而不是基線。

,瞧:

*, *:before, *:after { 
 
    box-sizing: inherit; 
 
} 
 
html { 
 
    box-sizing: border-box; 
 
} 
 

 
.parent { 
 
    width: 600px; 
 
    border: 1px solid black; 
 
    white-space: normal; 
 
} 
 

 
.parent:before { 
 
    content: "Before Pseudo Element"; 
 
    display: inline-block; 
 
    width: 50%; 
 
    border: 1px solid green; 
 
    vertical-align: top; 
 
} 
 

 
.parent div { 
 
    display: inline-block; 
 
    max-width: 50%; 
 
    border: 1px solid blue; 
 
    white-space: normal; 
 
}
<div class="parent"><div> 
 
    This is a string which is too long to fit in the parent next to it's :before pseudo selector 
 
</div></div>

+0

優秀!這對於評論HMTL中的空白是一個甜頭。 –

1

嘗試white-space屬性設置爲pre-wrap

1

我所做的跨度display:block;飄然與width:50%;:beforespan元素也不得不把box-sizing更改爲border-box,幫助多餘寬度,然後添加一個clearfix。

*, *:before, *:after{ 
 
    box-sizing:border-box; 
 
} 
 

 
.parent { 
 
    width: 600px; 
 
    border: 1px solid black; 
 
    white-space: normal; 
 
} 
 

 
.parent:after{ 
 
    content:""; 
 
    display:block; 
 
    clear:both; 
 
} 
 

 
.parent:before { 
 
    content: "Before Pseudo Element"; 
 
    display: inline-block; 
 
    width: 50%; 
 
    border: 1px solid green; 
 
    float:left; 
 
} 
 

 
.parent span { 
 
    display: block; 
 
    border: 1px solid blue; 
 
    white-space: normal; 
 
    float:left; 
 
    width:50%; 
 
}
<div class="parent"> 
 
\t <span> 
 
    This is a string which is too long to fit in the parent next to it's :before pseudo selector 
 
    </span> 
 
</div>

+0

另一個很好的答案,謝謝! –

0

只能設置:

.parent{ 
    display: flex; 
} 
.parent:before, .parent span { 
    flex: 1; 
    } 
+0

謝謝,這將是一個很好的解決方案,但我無法使用flexbox(我應該提到,在我的OP) –