居中图像并保持相同的高度

center image and keep same height

如何在不更改原始大小的情况下仅在父级 div 中使用 css 居中图像?

.main-img {
            display: block;
            width: 180px;
            overflow: hidden;
            align-self: flex-start;
        }
<div class="main-img">
  <img src="http://via.placeholder.com/300x50.png" width="1280px" height="550px" alt="main image" />
</div>

要水平居中您的元素,您正在寻找 margin: 0 auto,因为 <div> 元素默认为 block-level(因此你实际上并不需要 display: block):

.main-img {
  margin: 0 auto;
  width: 180px;
  overflow: hidden;
  align-self: flex-start;
}
<div class="main-img">
  <img src="http://via.placeholder.com/300x50.png" width="1280px" height="550px" alt="main image" />
</div>

垂直居中稍微复杂一点,用flexbox实现水平和垂直居中最简单,利用display: flex,align-items: centerjustify-content: center 属性 值。请注意,您还需要指定 height 属性:

.main-img {
  height: 180px;
  border: 1px solid black;
  display: flex;
  align-items: center;
  justify-content: center;
}

.main-img img {
  width: 140px;
  height: 140px;
}
<div class="main-img">
  <img src="http://via.placeholder.com/140x140.png" alt="main image" />
</div>

希望对您有所帮助! :)

方式一: 横向:

.main-img img {
  display: block;
  margin: auto;
}

垂直:

.main-img {
  height: 180px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.main-img img {
  width: 200px;
  height: 200px;
}

方式二: 横向:

.main-img {
  /* ... other code here such as width and height ... */
  position: relative;
}
.main-img img {
  position: relative; 
  left: 50%;
  transform: translateX(-50%);
}

垂直:

.main-img {
  /* ... other code here such as width and height ... */
  position: relative;
}
.main-img img {
  position: relative; 
  top: 50%; 
  transform: translateY(-50%);
}

纵横:

.main-img {
  /* ... other code here such as width and height ... */
  position: relative;
}
.main-img img {
  position: relative; 
  top: 50%; 
  left: 50%;
  transform: translate(-50%, -50%);
}