2015-02-23 46 views
4

我有一個小的挑戰,我沒有找到任何解決方案堆棧溢出。文本正在使用絕對定位

這就是我的了:

wrong

這就是我想它:

correct

爲了製造我使用絕對這個標題效果位置。我甚至不知道我的頭銜的寬度和高度。因此,使用此解決方案時,大文本會中斷。

我的HTML:

<div class="content"> 
    <h1 class="title">February 2015</h1> 
    <p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo. Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p> 
</div> 

我的CSS:

.content { 
    border: 3px double black; 
    padding-top: 60px; 
    position: relative; 
    width: 350px; 
} 

.content p { margin: 20px; } 

.title { 
    background: black; 
    border-radius: 5px; 
    color: white; 
    left: 50%; 
    padding: 10px; 
    position: absolute; 
    text-align: center; 
    transform: translate(-50%, -50%); 
    top: 0; 
} 

查看Codepen一個例子,讓生活更輕鬆: http://codepen.io/caio/pen/ZYoyPb

回答

11

最簡單的解決辦法是將添加white-space: nowrap。這樣做,h1文本不會破壞到一個新的行。 (updated example)

.title { 
    white-space: nowrap; 
    background: black; 
    border-radius: 5px; 
    color: white; 
    left: 50%; 
    padding: 10px; 
    position: absolute; 
    text-align: center; 
    transform: translate(-50%, -50%); 
    top: 0; 
} 

此外,你還可以添加text-overflow: ellipsis/overflow: hidden/width: 100%使得文本形成省略號,從來沒有突破到一個新的生產線。 (example here)

+0

真棒!謝謝... :) – 2015-02-23 18:53:35

2

在這裏,我已經爲你做了一些小的CSS更改。

/* Cosmetics */ 
* { box-sizing: border-box; } 
body { margin: 50px; } 
p { margin: 0; } 


/* True Code */ 
.content { 
    border: 3px double black; 
    padding-top: 30px; 
    position: relative; 
    width: 350px; 
} 

.content p { margin: 20px; } 

.title { 
    background: black; 
    border-radius: 5px; 
    color: white; 
    left: 50%; 
    padding: 10px; 
    position: absolute; 
    text-align: center; 
    transform: translate(-50%, -50%); 
    top: 0; 
    white-space: nowrap; 
    margin-top: 0px; 
} 
1

你的代碼是正確的,但左邊的屬性會破壞你的輸出。因爲.content div被設置爲相對的,.title將保留在其中。所以你只需要改變你的.title使用transform的位置:translate();碼。 瞧,你有你想要的輸出。

您可能會注意到我已經給.content提供了padding-top,只是將標題放置在適當的位置。

改變的代碼如下:

/* Cosmetics */ 
* { box-sizing: border-box; } 
body { margin: 50px; } 
p { margin: 0; } 


/* True Code */ 
.content { 
    border: 3px double black; 
    padding-top:10px; 
    position: relative; 
    width: 350px; 
} 

.content p { margin: 20px; } 

.title { 
    background: black; 
    border-radius: 5px; 
    color: white; 
    padding: 10px; 
    position: absolute; 
    transform: translate(22%,-110%); 
}