在div标签后的div标签内显示图像

时间:2020-07-20 14:47:59

标签: html css

我该如何更改?

enter image description here

仅使用CSS即可(图像位于该div内):

enter image description here

<style>
div {
    width: 70%;
    margin: 100px auto;
    border-radius: 5px;
    background-color: #FFF;
    box-shadow: 0 5px 15px rgb(150, 150, 150);
    padding-top:150px;
    padding-bottom:150px;
    position: relative;
}

div>img {
    position: absolute;
    width: 80px;
}
</style>

<div>
    <img class="first-square" src="img1.png" alt="">
</div>

3 个答案:

答案 0 :(得分:0)

position: absolutetransform: translate(<value for X coordinate>, <value for Y coordinate>)将完成工作。

尝试一次,如果仍然有疑问,我将向您展示它的工作原理。

快乐编码:)

编辑1:

.small-div{
  height: 50px; 
  width: 50px;
  position: absolute; 
  z-index: -100; 
  background-color: aqua;
  top: 0; 
  left : 0; 
  transform: translate(-50%, -50%); 
  border: 2px solid red
}
.larger-div{
  position: relative; 
  height: 200px; 
  width: 200px; 
  border: 2px solid black;
  background-color: white;
}
<div class="larger-div">
  <div class="small-div">
    // put img here
  </div>
</div>

答案 1 :(得分:0)

您可以尝试一下。

HTML

<div id="root">
   <div id="square"></div>
   <img src="https://placehold.it/100x100.png" alt="Image"/>
</div>

CSS

#square {
   width: 70%;
   margin: 100px auto;
   border-radius: 5px;
   background-color: #000;
   box-shadow: 0 5px 15px rgb(150, 150, 150);
   padding-top: 150px;
   padding-bottom: 150px;
   position: relative;
   z-index: 2;
}

#root > img {
   width: 80px;
   position: absolute;
   top: 15%;
   left: 10%;
   z-index: 1;
}

答案 2 :(得分:-2)

使用CSS constrained-categories属性。 z-index比另一个元素低的元素将排在后面(请注意,位置必须不是z-index之外的元素):

static