2017-08-31 59 views
0

我有一個頁面,其中我有多個全角<img>的 - 我必須添加一個<button><h2>疊加在每個圖像上。圖像將具有可變高度,因此內部元素需要符合其寬度+高度設置的邊界。文字和按鈕全寬圖像

的圖像因而風格:

CSS

.FullWidthImg { 
    width: 100vw; 
    position: relative; 
    left: 50%; 
    right: 50%; 
    margin-left: -50vw; 
    margin-right: -50vw; 
} 

HTML

<div id="container"> <!--ONLY STYLING FOR container IS position: relative--> 
    <img src="xx" alt="xx" style="FullWidthImg"/> 
    <h2>TEXT GOES HERE</h2> 
    <button>i'm a button</button> 
</div> 

大多數方法建議的造型<h2><button>position: absolute - 這工作,如果你有一個圖像元素和圖像總是有相同的高度,但是對我來說也不是這樣。

另一種方法我已經看到了正在是這樣的:

<div style="background-image: url(/img.com)"> 
    <h2>TEXT GOES HERE</h2> 
    <button>i'm a button</button> 
</div> 

...然後定位中,元素可能工作,但我想,以避免線造型如果可能的話。

是否有任何替代方法可用於此用例?

+1

我不認爲你提出哈克任何一個解決方案。關於第一個解決方案 - 「這適用於如果你有一個圖像元素和圖像總是具有相同高度」 - 所有你需要的是將每組img,h2和按鈕包裝在不同的div中。 –

+0

爲什麼第二個選項必須是內聯樣式?只需添加一個唯一的ID或類,並將樣式移動到您的CSS文件。 –

+0

@William_Wilson除非有什麼我不知道,你需要內聯樣式,因爲每個'背景圖像'必須有所不同。如果您使用課程,則只能有一個圖像。如果您使用ID - 您必須爲每個圖像創建一個單獨的ID。你仍然可以使用class/id,但需要使用'style'內聯來更改'background-image'。 – SamYoungNY

回答

1

建立你的第一個建議,這裏是你如何能夠完成你想要的佈局沒有內聯樣式。

.img-wrapper { 
 
    position: relative; 
 
} 
 

 
.img-wrapper img { 
 
    width: 100%; 
 
} 
 

 
.img-wrapper .overlay { 
 
    position: absolute; 
 
    top: 0; left: 0; right: 0; bottom: 0; 
 
    display: flex; 
 
    flex-direction: column; 
 
    align-items: center; 
 
    justify-content: center; 
 
    text-align: center; 
 
} 
 

 
.img-wrapper h2 { 
 
    margin: 0 0 .5em; 
 
}
<div class="img-wrapper"> 
 
    <img src="http://via.placeholder.com/600x150/eee/ddd" /> 
 
    <div class="overlay"> 
 
    <h2>Heading</h2> 
 
    <button>Button</button> 
 
    </div> 
 
</div> 
 

 
<div class="img-wrapper"> 
 
    <img src="http://via.placeholder.com/600x400/eee/ddd" /> 
 
    <div class="overlay"> 
 
    <h2>Heading</h2> 
 
    <button>Button</button> 
 
    </div> 
 
</div>

+0

謝謝,我現在正在嘗試這種方法 – SamYoungNY