我试图在具有背景图像的Button上添加一个渐变,同时将其悬停,而渐变不会影响/覆盖文本。
div.test {
background-image: linear-gradient(to right, #f9f9f9, #a2a2a2, #f9f9f9);
opacity: 0;
position: absolute;
width: 260px;
height: 80px;
margin-top: -23.5px;
z-index: 2;
}
div.test:hover {
opacity: 0.2;
}
div.menuleftbutton {
position: absolute;
width: 260px;
height: 80px;
margin: 150px 8% 0px;
background-color: blue; /* this would be replaced by an image */
}
div.menuleftbuttontext {
margin: 23.5px 0px 23.5px;
background-color: yellow;
font-size: 33px;
height: 33px;
}
<div class="menuleftbutton">
<div class="menuleftbuttontext">
<div class="test">
</div>
TEXT GOES HERE
</div>
</div>
jsfiddle中的全部内容: https://jsfiddle.net/fm6q95wk/1/
预期结果是在文本“下方”添加了渐变,而该版本没有。
到目前为止,我尝试过的每个版本要么在文本上放置渐变,要么在鼠标悬停在文本上方时不显示渐变。
答案 0 :(得分:1)
我已经修改了HTML,因此您只有一个div
内部和一个外部。
我更改了CSS,因此实质上是内部div设置了外部div的宽度和高度。这是因为您希望悬停效果覆盖整个“按钮”,并且我将悬停渐变放在内部div上,而外部div获取背景图像。阅读CSS中的注释,在其中解释每个规则的作用。
请注意在linear-gradient
上使用RGBA。这样,您就可以控制渐变的不透明度,我使用0.5
来实现不透明度,因此更容易看到悬停时的变化,但是您可以轻松地将其更改回0.2,以实现精确的外观。如果需要,可以在http://hex2rgba.devoth.com/处进行十六进制到RGBA转换器。
* {
box-sizing: border-box;
}
.menuleftbutton {
position: absolute;
background-image: url(https://picsum.photos/200); /* background-image */
background-repeat: no-repeat;
background-size: cover;
background-position: center;
margin: 0; /* just for the demo, change the margin to whatever you need */
cursor: pointer; /* hover... this makes it feel much more like a button */
}
.menuleftbuttontext {
width: 260px;
height: 80px;
font-size: 26px; /* decreased the size because it was splitting into 2 lines */
padding: 0 20px; /* keep text from hitting sides */
line-height: 80px; /* line-height same as height vertically centers text */
}
.menuleftbutton:hover .menuleftbuttontext { /* style of inner div when outer div is hovered */
background-image: linear-gradient(to right, rgba(249, 249, 249, 0.5), rgba(162, 162, 162, 0.5), rgba(249, 249, 249, 0.5));
}
<div class="menuleftbutton">
<div class="menuleftbuttontext">
TEXT GOES HERE
</div>
</div>
答案 1 :(得分:0)
position: absolute
才能将文本与按钮背景分开。这是我想出的:
html:
<body>
<div id="menuleft">
<div id="menuleftsticky">
<a href="">
<div class="menuleftbutton">
<div class="menuleftbuttontext">
<div class="test">
</div>
<div class="buttontext">
TEST
</div>
</div>
</div>
</a>
</div>
</div>
</body>
CSS:
div.buttontext {
position: absolute;
color: black;
z-index: 3;
width: 100%;
height: 0;
top: 30%;
}