首页 > 解决方案 > 将任意大小的图像居中对齐到父 div

问题描述

我有一个图像滑块,所选图像设置为上面的主图像。所有图像的大小都不相同。如何确保每个图像在父 div 和整个父 div 中居中?

我现在正在这样做:

width: 100%;height: 100%;object-fit:fill;

但随后我的图像丢失了其内容的底部。我想将图像垂直居中。

我的父 div 具有以下类风格:

.wrapper_image{
    max-width:100%;
    max-height:100%;
    min-height:100%;
    min-width: 100%;
    margin: 0 auto;
}

代码:

<div class="o-grid__col u-12/12" style="width: 400px;
          height: 400px;
          position: relative;
          display: inline-block;
          overflow: hidden;
          text-align: center;
          margin: 0;">
          <div class="mySlides wrapper_image_horses">
          <img src='url' style="width: 100%;height: 100%;object-fit:fill;">
          </div>
</div>

标签: htmlcss

解决方案


我建议你使用display: flex;来实现这一点。使用 flex,您可以更轻松地将图像垂直和水平居中对齐。下面是我做过的测试代码。希望对您的问题有所帮助

HTML

<div class="d-flex h-100">
  <div class="img-slide">
    <img src="https://via.placeholder.com/150">
  </div>
</div>

CSS

.d-flex {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}

.h-100 {
  height: -webkit-fill-available;
}

JS 小提琴链接:https ://jsfiddle.net/SJ_KIllshot/y5fzvox8/


推荐阅读