2013-03-26 88 views
0

我有兩件事情共享部分 - 一個由文本組成的頭部,一張浮動在其右側的圖像。我希望圖像寬度始終爲308px,並根據文本長度的需要裁剪其高度。我沒有興趣爲.location設置固定高度,因爲內容長度可能會改變。如何才能做到這一點? (謝謝!)CSS - 裁剪圖像高度以匹配文本長度

的HTML:

<section class="location"> 
<img src="http://evinwolverton.com/img/disc.jpg"> 
<header> 
    <h2>This Is A Headline</h2> 
    Etiam porta sem malesuada magna<br/> 
     Mollis euismod. Duis mollis<br/> 
     Est non commodo luctus, nisi erat<br/> 
     Porttitor ligula, eget lacinia odio<br/> 
     Sem nec elit. 
</header> 
</section> 

的CSS:

.location { 
    border: 2px solid #ccc; 
    overflow: hidden; 
    width: 620px; 
    color: #666; 
    margin: 40px 0; 
} 

.location header { 
    float: left; 
    padding: 25px; 
    width: 258px; 
} 

.location h2 { 
    margin: 0 0 10px 0; 
    font-size: 1.2em; 
    color: #333; 
} 

.location img { 
    float: right; 
    width: 308px; 
} 

回答

2

替代解決方案,以使用背景圖片,如果你想這是一個實際的<img>標籤將定位.location相對,保持溢出隱藏在這裏&給圖像的絕對位置。 您可能還需要在文本持有者上留出一些保證金,以確保它不會落在圖片後面。

.location { 
    position: relative; 
    overflow: hidden; 
} 
.location img { 
    position: absolute; 
    top: 0px; 
    right: 0px; 
} 
+0

有趣!如何用這種技術來限制圖像尺寸? – pianofighter 2013-03-26 23:45:48

+0

現在明白了。謝謝! – pianofighter 2013-03-27 00:36:59

0

最簡單的方法是使用對齊到右上角有一個no-repeatbackground-image

+0

男人,我希望我能做到這一點,但它必須是一個帶有錨標記的img。 – pianofighter 2013-03-26 23:32:49

0

如果您的圖像不需要是img標記,則可以將其作爲背景圖像應用到標題。但我認爲情況並非如此。

嘗試:

.location img { 
    position:absolute; 
    clip:rect(0px,60px,200px,0px); 
} 

http://www.w3schools.com/cssref/pr_pos_clip.asp

[編輯]

很抱歉,請clip: rect(0px, 308px, 100%, 0px);我敢肯定你會需要有像漂浮你的頭裏面。

+0

好奇。謝謝!圖像確實需要是一個包裹在錨標籤中的img。 – pianofighter 2013-03-26 23:50:03