2017-02-14 59 views
2

我有一個div與社會鏈接,我想使背景色填充整個div時懸停任何不同顏色的錨取決於哪個鏈接懸停。如何擴大懸停元素的背景顏色填充整個家長

現在只能在錨文本下面更改背景。

我正在研究如何使用純CSS填充具有孩子背景顏色的整個父項。

#social { 
 
    width: 400px; 
 
    height: 300px; 
 
    position: relative; 
 
    font-size: 36px; 
 
    font-weight: bold; 
 
    text-align: center; 
 
} 
 
a:link { 
 
    text-decoration: none; 
 
    transition: all .5s ease; 
 
} 
 
a:hover { 
 
    color: white; 
 
} 
 
#facebook:hover { 
 
    background: #3b5998; 
 
} 
 
#twitter:hover { 
 
    background: lightblue; 
 
} 
 
#google-plus:hover { 
 
    background: tomato; 
 
} 
 
#instagram:hover { 
 
    background: lightgreen; 
 
}
<div id="social"> 
 
       <a id="facebook" href="#"> <span>Facebook</span></a><br> 
 
       <a id="twitter" href="#"> <span>Twitter</span></a><br> 
 
       <a id="google-plus" href="#"> <span>Google plus</span></a><br> 
 
       <a id="instagram" href="#"> <span>Instagram</span></a><br> 
 
</div>

回答

4

對於乍一看它看起來像另一個試圖改變父元素的風格,但有一種方法使用純CSS實現的效果。

方法是使用::after僞選擇器作爲錨點元素。我們需要將其定義爲絕對定位並設置爲父級的100%維度。爲了防止同胞重疊,我們需要減少僞選擇器的z-index屬性以將其呈現在文本下方。

這裏是一個片段:

#social { 
 
    width: 400px; 
 
    height: 300px; 
 
    position: relative; 
 
    font-size: 36px; 
 
    font-weight: bold; 
 
    text-align: center; 
 
} 
 
a::after{ 
 
    content: " "; 
 
    width: 100%; 
 
    height: 100%; 
 
    position: absolute; 
 
    top: 0; 
 
    left: 0; 
 
    z-index: -1; 
 
    border-radius: 20px; 
 
    background: transparent; 
 
    transition: background .5s ease; 
 
} 
 
a:link { 
 
    text-decoration: none; 
 
    transition: color .5s ease; 
 
} 
 
a:hover { 
 
    color: white; 
 
} 
 
#facebook:hover::after { 
 
    background: #3b5998; 
 
} 
 
#twitter:hover::after { 
 
    background: lightblue; 
 
} 
 
#google-plus:hover::after { 
 
    background: tomato; 
 
} 
 
#instagram:hover::after { 
 
    background: lightgreen; 
 
}
<div id="social"> 
 
       <a id="facebook" href="#"> <span>Facebook</span></a><br> 
 
       <a id="twitter" href="#"> <span>Twitter</span></a><br> 
 
       <a id="google-plus" href="#"> <span>Google plus</span></a><br> 
 
       <a id="instagram" href="#"> <span>Instagram</span></a><br> 
 
</div>

+0

這比更漂亮[你以前的解決方案(http://www.codeply.com/go/gvLumhaKhT),因爲它使用了' ::之後,而不是另一個「div」。 –

+0

@JuanMendes感謝您的建議。我甚至不知道SO上的Q&A模式。 – Banzay