方法一:使用Flexbox

.container {
  display: flex;
  justify-content: center;
}

.image {
  /* 图片宽度 */
  width: 200px;
  /* 图片高度 */
  height: auto;
}
<div class="container">
  <img class="image" src="path/to/image.jpg" alt="描述">
</div>

在这个例子中,.container 类被设置为 display: flex;,这意味着它将变成一个 flex 容器。justify-content: center; 属性使得所有子元素都在容器中水平居中。

方法二:使用Grid布局

.container {
  display: grid;
  place-items: center;
}

.image {
  /* 图片宽度 */
  width: 200px;
  /* 图片高度 */
  height: auto;
}
<div class="container">
  <img class="image" src="path/to/image.jpg" alt="描述">
</div>

在这个例子中,.container 类被设置为 display: grid;,然后使用 place-items: center; 属性来居中所有子元素。

方法三:使用绝对定位和transform

如果您不希望使用 Flexbox 或 Grid,另一种选择是使用绝对定位和 transform 属性。以下是一个示例:

.container {
  position: relative;
  width: 100%;
}

.image {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  /* 图片宽度 */
  width: 200px;
  /* 图片高度 */
  height: auto;
}
<div class="container">
  <img class="image" src="path/to/image.jpg" alt="描述">
</div>

在这个例子中,.container 类被设置为 position: relative;,而 .image 类则使用绝对定位和 transform: translateX(-50%); 来实现水平居中。

结论