我想创建一个响应式英雄图像,但似乎无法将图片元素居中放置在父div中。我已经检查了这些帖子:

Center image in div horizontally
Center align image within div horizontally
Center image element in parent div

正如在其他帖子中所建议的那样,我尝试使用margin: auto auto;position并将min-width设置为父div,但是图像仍保持最左对齐。
我要实现的目标的Here's an example

这是我的代码(我还创建了一个jsfiddle:https://jsfiddle.net/wuy44t9p/1/):

<style type="text/css">
    .profile-banner {
        display: block;
        height: 500px;
        position: relative;
    }

    .profile-banner picture {
        display: block;
        margin: 0 auto;
        position: absolute;
    }

</style>


<div id="CPHBigBanner_pnlCoverPhoto">
    <section class="profile-banner lazy">
        <picture class="profile-herobanner lazy" data-was-processed="true">
            <source type="image/webp" class="lazy" data-srcset="http://www.1001locaties.nl/images/tmp/41747_965_Owl.webp" srcset="/images/objphotos/covers/41747_965_Owl.webp" data-was-processed="true">
            <img class="lazy loaded" data-src="http://www.1001locaties.nl/images/tmp/41747_965_Owl.png" alt="" src="/images/objphotos/covers/41747_965_Owl.png" data-was-processed="true">
        </picture>
    </section>
</div>

最佳答案

根据我的评论,您需要从图像中删除绝对位置,还需要向容器添加文本对齐中心:



.profile-banner {
  display: block;
  height: 500px;
  text-align:center;
}

.profile-banner picture {
  display: block;
  margin: 0 auto;
}

<div id="CPHBigBanner_pnlCoverPhoto">
  <section class="profile-banner lazy">
    <picture class="profile-herobanner lazy" data-was-processed="true">
      <source type="image/webp" class="lazy" data-srcset="http://www.1001locaties.nl/images/tmp/41747_965_Owl.webp" srcset="https://via.placeholder.com/350x150" data-was-processed="true">
      <img class="lazy loaded" data-src="http://www.1001locaties.nl/images/tmp/41747_965_Owl.png" alt="" srcset="https://via.placeholder.com/350x150" data-was-processed="true">
    </picture>
  </section>
</div>

关于css - 在父div的中心对齐图片元素,使图片向左对齐,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50292506/

10-10 08:31
查看更多