如何使用 CSS text-align 属性将图像居中

通常,我们不能使用 CSS text-align 属性将图像居中,因为它仅适用于块元素,而 <img> 是内联元素。

但是有一个技巧可以使用 text-align 属性将图像居中。
如果由于某些原因需要此属性,可以添加一个 <div> 元素并在其上指定 text-align 属性。

使用此属性的“center”值。

使用 text-align 属性居中图像的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      div {
        border: 1px solid green;
        text-align: center;
      }
    </style>
  </head>
  <body>
    <h1>Example of centering an image </h1>
    <div>
      <img src="/car.jpeg" alt="car" width="200" height="185" />
    </div>
  </body>
</html>

让我们看另一个示例,其中通过将样式立即应用于 <img> 元素来使图像居中。
在这种情况下,我们必须将 <img> 的显示设置为“block”,并以“0 auto”为其值指定 margin 属性。

居中图像的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      div {
        border: 1px solid green;
      }      
      div img {
        display: block;
        margin: 0 auto;
      }
    </style>
  </head>
  <body>
    <h1>Example of centering an image</h1>
    <div>
      <img src="car.png" width="200" height="185" />
    </div>
  </body>
</html>
日期:2020-06-02 22:15:05 来源:oir作者:oir