使用 "center" 将图像水平居中

Centering an image horizontally using "center"

我无法将图像水平居中。这是我的代码:

<img src="https://dummyimage.com/300x200/000/fff" alt="johnson johnson" style="width:300px; height:225px;" class="center">

我做错了什么?谢谢你的时间。

你可以添加这个

<style>
.center {
    display: block;
    margin-left: auto;
    margin-right: auto;
    width: 50%;
}
</style>

我刚刚创建了您的 class 中心以使其居中图像

您需要将 left & right margin 应用到 auto;

Solution:

margin:0 auto;

display:block

<div style="border:solid 1px red">
<img src="https://dummyimage.com/300x200/000/fff" alt="johnson johnson" style="width:300px; height:225px;margin:0 auto;display:block">
</div>

如果您想在线设置样式,您可以使用中心标签

<center>
<img src="https://dummyimage.com/300x200/000/fff" alt="johnson johnson" style="width:300px; height:225px;">
<center>

只需在图片前添加 p 标签并为其添加样式即可。

 <p style="text-align:  center;">
     <img src="https://dummyimage.com/300x200/000/fff" alt="johnson johnson" style="width:300px;height:225px;>
 </p>