我在CSS中为HTML块添加功能时遇到了一些问题。以下是它应该如何工作:
问题如下:悬停时不仅图像增加,还有文本。我意识到可能所有下降都会扩展到1.25;但是,只有图像应缩放,而文本在半透明图层中间保持相同的大小。请帮我解决一下。
HTML:
<div class="container">
<div class="image-block">
<div class="layer">
<span>Whatever</span>
</div>
</div>
</div>
和CSS:
* {
margin: 0;
padding: 0;
border: 0;
font-family: sans-serif;
}
.container {
height: 20em;
width: 20em;
overflow: hidden;
}
.image-block {
height: 100%;
width: 100%;
background: url(http://a1.dspnimg.com/data/l/467928107631_M5V8zyVM_l.jpg) no-repeat center center;
background-size: cover;
transition: all 0.4s ease;
}
.layer {
height: 100%;
width: 100%;
background-color: rgba(0,0,0,0);
opacity: 0;
}
.image-block:hover .layer {
background-color: rgba(0,0,0,0.35);
opacity: 1;
}
.container:hover .image-block {
transform: scale(1.25);
}
并且jsfiddle也链接:http://jsfiddle.net/vorontsov/kL8Lb8pm/10/
答案 0 :(得分:0)
这是以文字为中心的。 Paulie_D和我做的唯一调整背景图片的方法是将transform: scale(1.25);
更改为background-size: 125%;
.container:hover .image-block
。您还需要在background-size: cover;
上将background-size: 100%;
更改为.image-block
。
示例:
.image-block {
height: 100%;
width: 100%;
background: url(http://a1.dspnimg.com/data/l/467928107631_M5V8zyVM_l.jpg) no-repeat center center;
background-size: 100%; /* This line was changed */
transition: all 0.4s ease;
}
.container:hover .image-block {
background-size: 125%; /* This line was changed */
}
要垂直和水平居中对齐需要添加的文字:
.layer {
height: 100%;
width: 100%;
background-color: rgba(0,0,0,0);
opacity: 0;
text-align: center;
display: table; /* this line was added */
}
/* This whole block was added */
.layer span {
width: 100%;
height: 100%;
display: table-cell;
vertical-align: middle;
}
以下是一个完整的工作示例:
* {
margin: 0;
padding: 0;
border: 0;
font-family: sans-serif;
}
.container {
display: table;
height: 20em;
width: 20em;
overflow: hidden;
}
.image-block {
height: 100%;
width: 100%;
background: url(http://a1.dspnimg.com/data/l/467928107631_M5V8zyVM_l.jpg) no-repeat center center;
background-size: 100%;
transition: all 0.4s ease;
}
.layer {
height: 100%;
width: 100%;
background-color: rgba(0,0,0,0);
opacity: 0;
text-align: center;
display: table;
}
.layer span {
width: 100%;
height: 100%;
display: table-cell;
vertical-align: middle;
}
.image-block:hover .layer {
background-color: rgba(0,0,0,0.35);
opacity: 1;
}
.container:hover .image-block {
background-size: 125%;
}
<div class="container">
<div class="image-block">
<div class="layer">
<span>Whatever</span>
</div>
</div>
</div>