如何让我的图像在绝对块中保持响应?

我拼命地尝试将我的图像放在 2 个 div 块之间,并且这个块具有响应能力。


我建议拍摄方形图像,因为如您所见,我希望我的图像适合圆形,并且由于高度在我的绝对块中设置为自动(因为我想保持响应行为),因此形状将是矩形。


html, body {

      width: 100%;

      height: 100%;

}

.child1 {

      width: 100%;

      height: 200px;

      background-color: red;

}

.child2 {

      width: 100%;

      height: 200px;

      background-color: green;

}

.main {

      position: relative;

      width: 100%;

}

.absolute-block {

      position: absolute;

      top: 25%;

      left: 40%;

      width: 16%;

      border: 2px solid yellow;

}

img {

      height: 100%;

      width: 100%;

      border-radius: 50%;

      border: 5px solid white;

}

<body>

  <div class="main">

    <div class="absolute-block">

      <img src="test.jpg">

    </div>

    <div class="child1"></div>

    <div class="child2"></div>

  </div>

</body>

因此,如果一切顺利,它应该看起来像这样:

https://img1.sycdn.imooc.com/65818eed00014ea706500223.jpg

现在,当我尝试水平缩小窗口的大小时,我希望图像的大小垂直和水平缩小(好的,可以),并且我希望图像的中心保持在 2 个 div 之间(它不& #39;不起作用)。我可以对代码进行哪些更改才能获得此结果?



慕容森
浏览 62回答 2
2回答

心有法竹

首先将绝对块放在容器中间居中,我们可以这样做top:&nbsp;50%; left:&nbsp;50%; transform:&nbsp;translate(-50%,-50%);top&nbsp;和&nbsp;left&nbsp;将根据元素的左上角定位元素,然后我们使用 Transform 根据元素自身的方向将元素在两个方向上移动一半宽度和高度。现在,一旦块完全居中,我们就可以在其中添加我们想要的任何内容。* {&nbsp; padding: 0;&nbsp; margin: 0;&nbsp; box-sizing: border-box;}html,body {&nbsp; width: 100%;&nbsp; height: 100%;}.child1 {&nbsp; width: 100%;&nbsp; height: 200px;&nbsp; background-color: red;}.child2 {&nbsp; width: 100%;&nbsp; height: 200px;&nbsp; background-color: green;}.main {&nbsp; position: relative;&nbsp; width: 100%;}.absolute-block {&nbsp; position: absolute;&nbsp; top: 50%;&nbsp; left: 50%;&nbsp; transform: translate(-50%, -50%);&nbsp; width: 16%;&nbsp; border: 2px solid yellow;}img {&nbsp; max-height: 100%;&nbsp; max-width: 100%;&nbsp; border-radius: 50%;&nbsp; border: 5px solid white;}<div class="main">&nbsp; <div class="absolute-block">&nbsp; &nbsp; <img src="https://i.picsum.photos/id/353/300/300.jpg">&nbsp; </div>&nbsp; <div class="child1"></div>&nbsp; <div class="child2"></div></div>

慕尼黑5688855

您想尝试以下方法吗?img {&nbsp; width: 100%;&nbsp; height: auto;&nbsp; position: relative;&nbsp; top: 50%;&nbsp; -ms-transform: translateY(-50%);&nbsp; -webkit-transform: translateY(-50%);&nbsp; transform: translateY(-50%);}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5