【问题标题】:how to center Items that are not in div or span in html/css如何在 html/css 中将不在 div 或 span 中的项目居中
【发布时间】:2022-01-26 18:45:21
【问题描述】:

我有时会构建我的 html 网站,并且在我完成后需要添加一些我没想到会在开头添加的东西,例如行之间的图像,所以我只是打开 img 标签并放置图像而不将其放入div 或跨度。所以问题是我不知道如何居中。无论如何,有没有将一个有父容器的项目居中?这是一个示例代码

<html><img src="img.jpg" alt="img"></html> <style>text-align: center;</style>

此代码的问题在于它使我也尝试使用的所有可以居中的属性都居中,例如“justify-content: center; or align-items: center;”但是 img 完全移动了,我只能通过使用 padding 或 margin 来移动它,这不是最好的方法。

有没有人知道我如何将一个项目居中,该项目有一个像 div 这样的父容器或这个项目在 html/css 中工作?

【问题讨论】:

    标签: html css center division


    【解决方案1】:

    您可以将显示属性定义为“flex”。

    <html><img src="img.jpg" class="Myimg"></html>
    
    .Myimg
    {
    display: flex;
    justify-content: center;
    }
    

    【讨论】:

    • 感谢您的回答。它实际上可以工作,但不完全是我想要的方式,因为在这种情况下,我必须将 img 放在一个 div 中,然后给这个 div 一个显示: flex;能够使用 justify-content: center;这就是我不想使用的。我想要它没有 div 但仍然感谢您的回答
    【解决方案2】:

    如果您想修复代码以使其正常工作,请务必在代码的 style 部分添加 html。像这样:

    &lt;html&gt;&lt;img src="img.jpg" alt="img"&gt;&lt;/html&gt; &lt;style&gt;html { text-align: center; }&lt;/style&gt;

    但这会让一切都居中。如果您只希望图像居中,请执行以下操作: &lt;html&gt;&lt;img src="img.jpg" id="myimage" alt="img"&gt;&lt;/html&gt; &lt;style&gt;#myimage { text-align: center; }&lt;/style&gt;

    关于使用 display:blockmargin:0 auto 的替代解决方案(其他人已经在此处发布)——这也是可行的。

    有两种方法可以为您工作:

    选项 1:

    &lt;html&gt;&lt;img src="img.jpg" style="display:block; margin:0 auto;" alt="you should probably leave alt blank if the image is decorative, otherwise actually describe what it is"&gt;&lt;/html&gt; &lt;style&gt;html { text-align: center; }&lt;/style&gt;

    选项 2:

    &lt;html&gt;&lt;img src="img.jpg" id="#myimage" alt="img"&gt;&lt;/html&gt; &lt;style&gt;#myimage{ display:block;margin: 0 auto; }&lt;/style&gt;

    归根结底,它归结为实际学习 CSS 以及样式表的工作原理。您可能想对此进行一些学习,在 youtube 和网站上查找一些“学习 CSS”的视频——这是一些核心内容,所以如果您还不了解它,请多研究一些基础知识。

    【讨论】:

      【解决方案3】:

      对于图片,您可以使用display: blockmargin:0 auto,例如:&lt;img src="img.jpg" style="display:block; margin:0 auto;" alt="img"&gt;

      补充阅读:https://www.freecodecamp.org/news/how-to-center-an-image-in-css/

      【讨论】:

        猜你喜欢
        • 2013-09-15
        • 1970-01-01
        • 2017-02-28
        • 2022-12-03
        • 2014-06-11
        • 2013-07-20
        • 2022-11-10
        • 2020-08-20
        • 1970-01-01
        相关资源
        最近更新 更多