如何将图像叠加到div元素上

问题描述 投票:0回答:2

我有一个基本上是矩形边框的元素,其中包含一些主要由文本组成的其他元素。

当我将鼠标悬停在元素上时,我需要知道如何将图像叠加到这个矩形边框元素上。

以下是我的代码。到目前为止,我已经能够覆盖一个红色矩形,但我不确定如何覆盖图像。

.container {
  position: relative;
  width: 100px;
  ;
  max-width: 400px;
}

.overlay {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100px;
  width: 100px;
  opacity: 0;
  transition: .3s ease;
  background-color: red;
}

.container:hover .overlay {
  opacity: 1;
}

#square {
  background-color: grey;
  width: 100px;
  height: 100px;
}
<div class="container">
  <div id="square">
  </div>
  <div class="overlay">
    <a href="#"> </a>
  </div>
</div>
css html5
2个回答
1
投票

HTML

<div class="rectangle-wrapper">
  <h1>Big Title</h1>
  <p>Long description. Probably needs to be longer. Lorem ipsummmmmm.</p>
</div>

CSS

.rectangle-wrapper {
border: 5px solid black;
}


.rectangle-wrapper:hover {
  background-image: url(https://via.placeholder.com/350x150);
  background-repeat:no-repeat;
  background-size:cover;
  background-position: center center;
}

小提琴:https://jsfiddle.net/srtk05mx/2/

编辑:使用您的代码小提琴:https://jsfiddle.net/srtk05mx/3/

现在,如果你真的想要只在边框上的图像,你将不得不使用不同的技术。


0
投票

您可以通过background-color更改background-image并通过更改#square设置背景属性并将opacity从1更改为更小,如0.3

#square {
  background-image: url('https://cdn.pixabay.com/photo/2016/07/21/15/14/girl-1532733_960_720.jpg');
  width: 100px;
  height: 100px;
  background-repeat: no-repeat;
  background-size: cover;
}

.container {
  position: relative;
  width: 100px;
  ;
  max-width: 400px;
}

.overlay {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100px;
  width: 100px;
  opacity: 0;
  transition: .3s ease;
  background-color: red;
}

.container:hover .overlay {
  opacity: .3;
}

#square {
  background-image: url('https://cdn.pixabay.com/photo/2016/07/21/15/14/girl-1532733_960_720.jpg');
  width: 100px;
  height: 100px;
  background-repeat: no-repeat;
  background-size: cover;
}
<div class="container">
  <div id="square">
  </div>
  <div class="overlay">
    <a href="#"> </a>
  </div>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.