2016-12-04 60 views
-1

我在創建背景圖片頂部的透明框時遇到問題,如this。我的代碼幾乎完全一樣,但由於某種原因,我無法讓透明框從圖像的頂部移開(我希望框的上邊和下邊有一些邊距)。添加填充:20px到.background什麼也不做;將margin:20px添加到#transbox只會將左右邊距增加20px,但對頂部和底部邊距沒有任何影響。在圖像頂部的透明框中的文本?

HTML CSS &:

.background { 
 
    background-image: url("https://source.unsplash.com/5OMTuqOM7bI"); 
 
} 
 
#transbox { 
 
    background-color: rgba(255, 255, 255, 0.8); 
 
    padding: 20px; 
 
    margin: 60px; 
 
} 
 
h3 { 
 
    text-align: center; 
 
    font-weight: 300; 
 
    color: #3C5FA3; 
 
} 
 
.container { 
 
    width: 80%; 
 
    margin: 0 auto; 
 
    padding: 0 30px; 
 
} 
 
.clearfix:after { 
 
    visibility: hidden; 
 
    display: block; 
 
    content: ""; 
 
    clear: both; 
 
    height: 0; 
 
}
<div class="container clearfix background"> 
 
    <div id="transbox"> 
 
    <h3>Some text here</h3> 
 
    </div> 
 
</div>

+0

'padding:0 30px;'與'padding-top:0;'相同。 padding-right:30px; padding-bottom:0; padding-left:30px;' – connexo

+1

*將'padding:20px;'添加到'.background'什麼都不做*這是因爲在以後的CSS中,您會在'.container'中覆蓋此填充。 – connexo

回答

0

幾種途徑來得到這個。其中之一是設置容器的padding-top/bottom。 (不是padding: 0 30px)。

這裏是修復你的代碼:

.background { 
 
    background-image:url("https://source.unsplash.com/5OMTuqOM7bI"); 
 
} 
 

 
#transbox { 
 
    background-color:rgba(255,255,255,0.8); 
 
    padding:20px; 
 
    margin:60px; 
 
} 
 

 
h3 { 
 
    text-align:center; 
 
    font-weight:300; 
 
    color:#3C5FA3; 
 
} 
 

 
.container { 
 
    width: 80%; 
 
    margin: 0 auto; 
 
    padding: 30px; 
 
} 
 

 
.clearfix:after { 
 
    visibility:hidden; 
 
    display:block; 
 
    content:""; 
 
    clear:both; 
 
    height:0; 
 
}
<div class="container clearfix background"> 
 
    <div id="transbox"> 
 
     <h3>Some text here</h3> 
 
    </div> 
 
</div>

0

你不需要這種情況下的clearfix或任何東西。所有你需要的是背景不透明度。這裏的關鍵是給容器:

  • position: relative;
  • height: <some>px;

而且transbox

  • position: absolute;
  • topright值。

如果你想要它是中心,這很容易。使用死點招這樣的:

.background { 
 
    background-image: url("https://source.unsplash.com/5OMTuqOM7bI"); 
 
} 
 
#transbox { 
 
    background-color: rgba(255, 255, 255, 0.8); 
 
    padding: 20px; 
 
    margin: 60px; 
 
    position: absolute; 
 
    top: 50%; 
 
    left: 50%; 
 
    transform: translate(-50%, -50%); 
 
} 
 
h3 { 
 
    text-align: center; 
 
    font-weight: 300; 
 
    color: #3C5FA3; 
 
} 
 
.container { 
 
    width: 80%; 
 
    margin: 0 auto; 
 
    padding: 0 30px; 
 
    position: relative; 
 
    height: 500px; 
 
}
<div class="container background"> 
 
    <div id="transbox"> 
 
    <h3>Some text here</h3> 
 
    </div> 
 
</div>

最初版本

preview

中心版

preview

0

padding: 0 30px;是相同的padding-top: 0; padding-right: 30px; padding-bottom: 0; padding-left: 30px;

你說:

添加padding: 20px;.background什麼都不做

那是因爲後來在你的CSS你.container覆蓋此填充。

如果兩個或更多規則具有相同的CSS特性,則最後發生的規則將勝出。由於這兩個選擇器具有相同的特異性,因此定義的.container勝過.background定義。