2016-04-28 60 views
1

我具有其中的所有內容(<h1><h2><p>等)包含在<div>內一個簡單的頁面,以便具有相同的標題的背景圖像寬度。延伸到頁面的與CSS的邊緣和頂部

我喜歡正文文本的外觀,並希望保持它的方式,但我想添加一個背景圖片到標題。它應該從頁面的頂部開始(在我的情況下是窗口),並且結束於標題本身最後一行的基線,同時也從窗口左側向右側延伸。在下面的圖片中,我說明了所需的佈局。在它下面,我繪製了我嘗試過的html層次結構。

enter image description here

事實上,我已經嘗試創建的<h1>一個孩子

width: 100vw; 
position: relative; 
left: 50%; 
transform: translate(-50%); 

但:

  1. 由於頁面具有z-index: -1;,一些奇怪的錯誤,我可以不要點擊相對定位鏈接
  2. 我不想使用vw因瀏覽器支持而聯合。
  3. 我仍然無法設法將背景延伸到頂部。

<h1>及其邊緣是以像素爲單位定義,如您所看到的字體大小,但頁面仍然表現動態因爲我調整窗口的大小,的<h1>增加行數。

HTML

<div class="page"> 
    <h1>Heading</h1> 
    <h2>Section 1</h2> 
     <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, 
      sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p> 
</div> 

CSS

body { 
    height: 100%; 
    width: 100%; 
    margin:0px; 
} 

.page { 
    font-size: 20px; 
    width: 90%; 
    max-width: 70ch; 
    padding: 50px 5%; 
    margin: auto; 
    z-index: -1; 
} 

h1 { 
    font-size: 30px; 
    margin-top: 0; 
    margin-bottom: 10px; 
} 

h2 { 
    font-size: 22px; 
    margin-bottom: 26px; 
} 

p {margin-bottom: 24px;} 

JS Fiddle

+2

大多數時候人們將寬度約束分離到自己的類中,並多次使用它。這樣,你把h1放在一個容器類的div裏面,然後你把它放在你想要有全寬背景的div中,然後頁面的其餘部分就落在它後面。像這樣:https://jsfiddle.net/fu2038vb/5/ – tylerism

回答

1

兩個建議:

將h1和身體的其餘部分分爲兩個不同的div。將背景應用於第一個div。

<div class="background-here"> 
<div class="page"> 
    <h1>Heading</h1> 
</div> 
</div> 
<div class="page"> 
    <h2>Section 1</h2> 
     <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, 
      sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p> 
</div> 

或者你可以只應用背景的身體和使用background-repeat: repeat-xbakcground-size: cover。但這取決於圖像的設計方式。