【问题标题】:How can I keep my image responsive in an absolute block? [duplicate]如何让我的图像在绝对块中保持响应? [复制]
【发布时间】:2020-07-26 00:04:01
【问题描述】:

我正在拼命尝试将我的图像放在 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>

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

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

【问题讨论】:

  • 有理由不使用简单的背景图片吗?
  • 您的意思是在绝对块中放置背景吗?如果我这样做,我需要指定一个高度并且我的图像不再响应

标签: html css


【解决方案1】:

你想试试关注吗,

img {
  width: 100%;
  height: auto;
  position: relative;
  top: 50%;
  -ms-transform: translateY(-50%);
  -webkit-transform: translateY(-50%);
  transform: translateY(-50%);
}

【讨论】:

  • 感谢您的快速回复。但是,问题是我在图像的初始位置有很大的差距。这就是我使用绝对位置的原因
【解决方案2】:

首先将绝对块放在容器中间,我们可以这样做

top: 50%;
left: 50%;
transform: translate(-50%,-50%);

topleft 将根据元素的左上角定位元素,然后我们使用变换将元素根据它自己的宽度和高度在两个方向上移动一半。

现在,一旦块完全居中,我们就可以在其中添加任何我们想要的内容。

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

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: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 16%;
  border: 2px solid yellow;
}

img {
  max-height: 100%;
  max-width: 100%;
  border-radius: 50%;
  border: 5px solid white;
}
<div class="main">
  <div class="absolute-block">
    <img src="https://i.picsum.photos/id/353/300/300.jpg">
  </div>
  <div class="child1"></div>
  <div class="child2"></div>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-04
    • 1970-01-01
    • 1970-01-01
    • 2014-03-01
    • 1970-01-01
    • 2018-09-10
    • 2014-05-09
    相关资源
    最近更新 更多