2016-05-27 63 views
8

我有一個包含兩行的div。頂線是標題,底線是名稱。CSS溢出左浮動

當標題足夠短,這個名字是在底線上(左圖)

然而,當標題很長,我想溢出轉到第二線,並有下一個名字像它在正確的形象。

有人可以幫助我嗎?

enter image description here

下面是HTML結構:

<div class="container"> 
    <div class="content_top"> 
     <span class="content">Something</span> 
    </div> 
    <div class="name_top"> 
     <span class="name">Steve</span> 
    </div> 
</div> 
+1

能否請您發佈您的代碼? – johnniebenson

+0

將換行符設置爲換行的兩個div(或tds),或者任何可以控制寬度的值。 –

回答

3

CSS技巧。將名稱放在下一行或同一個名稱上

我已經使用了:first-line僞元素和word-spacing屬性。

如果第一行很短,則名稱放在下一行。如果第一行很長,則該名稱放在同一行上。

請檢查結果:  codepen,  jsfiddle

/* heart of the matter */ 
 
.container:first-line { 
 
    word-spacing: 240px; /* the width of the container, or more */ 
 
} 
 
.content { 
 
    word-spacing: normal; 
 
} 
 
.insert { 
 
    margin-right: -11px; /* defined by the normal inter-word space */ 
 
} 
 

 
/* nice look */ 
 
.container { 
 
    border: 5px solid black; 
 
    float: left; 
 
    font-family: Helvetica; 
 
    font-size: 20px; 
 
    font-weight: bold; 
 
    margin: 0 15px 30px 0; 
 
    min-height: 60px; 
 
    padding: 8px 10px; 
 
    width: 240px; 
 
} 
 
.name { 
 
    color: red; 
 
} 
 

 
/* little explanation */ 
 
.colored-background .content { background-color: lightblue; } 
 
.colored-background .insert { background-color: orange; }
<div class="container"> 
 
    <span class="content">Something</span> 
 
    <span class="insert">&nbsp;</span> 
 
    <span class="name">Steve</span> 
 
</div> 
 
<div class="container"> 
 
    <span class="content">Something Something Else</span> 
 
    <span class="insert">&nbsp;</span> 
 
    <span class="name">Steve</span> 
 
</div> 
 

 
<div style="clear: left;"></div> 
 

 
<div class="container colored-background"> 
 
    <span class="content">Something</span> 
 
    <span class="insert">&nbsp;</span> 
 
    <span class="name">Steve</span> 
 
</div> 
 
<div class="container colored-background"> 
 
    <span class="content">Something Something Else</span> 
 
    <span class="insert">&nbsp;</span> 
 
    <span class="name">Steve</span> 
 
</div>

+1

非常感謝! =)另一個真棒技巧! – HEYHEY

0

如果標題是<h1>標籤例如,使用CSS樣式:

h1 { 
    text-align: left; 
} 
+1

謝謝你的回覆。我添加了一個我現在擁有的代碼。如有必要,我可以更改結構 – HEYHEY

+0

是不是標題塊元素?提及內聯! –