【问题标题】:Center image horizontally within a div在 div 内水平居中图像
【发布时间】:2012-06-14 21:32:02
【问题描述】:

这可能是一个愚蠢的问题,但由于通常的居中对齐图像的方法不起作用,我想我会问。如何在其容器 div 内居中对齐(水平)图像?

这里是 HTML 和 CSS。我还为缩略图的其他元素添加了 CSS。它按降序运行,所以最高的元素是所有东西的容器,最低的元素是所有东西的容器。

#thumbnailwrapper {
      color: #2A2A2A;
      margin-right: 5px;
      border-radius: 0.2em;
      margin-bottom: 5px;
      background-color: #E9F7FE;
      padding: 5px;
      border: thin solid #DADADA;
      font-size: 15px
}
    
#artiststhumbnail {
      width: 120px;
      height: 108px;
      overflow: hidden;
      border: thin solid #DADADA;
      background-color: white;
}
    
#artiststhumbnail:hover {
      left: 50px
}
<!--link here-->

<a href="NotByDesign">
  <div id="thumbnailwrapper">

    <a href="NotByDesign">

      <!--name here-->
      <b>Not By Design</b>
      <br>

      <div id="artiststhumbnail">

        <a href="NotByDesign">

          <!--image here-->
          <img src="../files/noprofile.jpg" height="100%" alt="Not By Design" border="1" />
        </a>
      </div>

      <div id="genre">Punk</div>

  </div>

好的,我已经添加了没有 PHP 的标记,所以应该更容易看到。这两种解决方案在实践中似乎都行不通。顶部和底部的文本不能居中,图像应在其容器 div 中居中。容器已隐藏溢出,所以我想看到图像的中心,因为它通常是焦点所在的位置。

【问题讨论】:

  • 是否打算将图像显示在与第一个链接(artisturl 之一)相同的行上?
  • imgtext-align: center 约束,除非他们的display 已被修改。
  • jsfiddle.net/cEgRp - 简单的text-align: center
  • Jacob,您至少可以发布浏览器看到的实际标记而不是注入 PHP 的模板吗?此外,一个正常运行的jsfiddle.net 总是有帮助的。
  • 别在意我的评论 - 我没有注意到 img 包含在 a 中。我很笨。

标签: html css


【解决方案1】:

是的,这样的代码可以正常工作

<div>
 <img/>
</div>

只是提醒你,图片的样式

object-fit : *depend on u*

所以最终的代码类似于示例

div {
  display: flex;
  justify-content: center;
  align-items: center;
}

div img {
  object-fit: contain;
}
<div style="border: 1px solid red;">
  <img src="https://img.joomcdn.net/9dd32cbfa0cdd7f48ca094972ca47727cd3cd82c_original.jpeg" alt="" srcset="" style="
       border-radius: 50%;
       height: 7.5rem;
       width: 7.5rem;
       object-fit: contain;" />
</div>

【讨论】:

    【解决方案2】:

    要使图像居中,请使用此 css。您必须在图像的开头给出宽度。

    img{
      width: 300px;
      position: fixed;
      left0;
      right:0;
    
    }
    

    【讨论】:

    • 这不是使图像居中的正确方法。
    【解决方案3】:

    Style.css

    img#center-img{
    
     display: block;
     margin: auto;
    }
    

    HTML

    <html>
      <body>
        <div>
          <img src='pic.png' id='center-img'>
        </div>
      </body>
    </html>
    

    【讨论】:

    • 请仅添加尚未提供的答案。碰巧,这与接受的答案相同。
    【解决方案4】:

    这样也行

    #imagewrapper {
        text-align:center;
    }
    
    #imagewrapper img {
        display:inline-block;
        margin:0 5px;
    }
    

    【讨论】:

    • 您的意思是 text-align:center;margin:0 5px; 吗?我添加了;
    • @jagb 分号对于选择器块中的最后一个属性不是必需的。
    • @TylerH 没错,选择器块中的最后一个属性不需要分号,但使用分号总是更省事。如果我写一个 CSS 文件,另一个开发人员稍后编辑我的文件怎么办,他们添加了一些代码(在缺少分号的行之后,我之前在那个 CSS 文件中写的行)并且它们的高度、宽度或其他声明不起作用(或者更糟糕的是,他们没有注意到它不起作用) .我会说把分号留在里面更安全。这就是为什么我使用分号并且从不把分号放在外面。
    • @jagb 如果其他开发人员稍后编辑您的文件,他们将在必要时添加分号,否则将是他们编写有错误的代码的问题。对您最初评论的回复仍然是:“CSS 中最后一行的分号是一种样式选择”。
    • 我同意 jagb。这个网站应该提倡好的风格选择。好的风格不会留下容易被破坏的代码。将分号放在每一行上可能会花费您 1/10 秒,调试以查找单个丢失的分号可能会花费您数小时。这就是为什么大型科技公司坚持它的原因:Google HTML/CSS Style Guide - Declaration Stops
    【解决方案5】:
    #artiststhumbnail a img {
        display:block;
        margin:auto;
    }
    

    这是我的解决方案:http://jsfiddle.net/marvo/3k3CC/2/

    【讨论】:

    • 我认为这不是一个好主意,而且我相信有一些警告,例如 margin: auto 依赖于具有指定宽度值的包含元素。
    • 我仍在提高我的 CSS 技能,感谢您提供有趣的学习点。但在这种情况下,他在容器上使用了固定宽度。
    • 在这种情况下,指定宽度究竟是什么意思?拥有绝对有用的知识。
    • 看到这个fiddle I made;我不知道该怎么想。你的建议不会做任何事情,我相信img 无论如何都需要定义一个宽度才能对auto 产生任何影响。
    • 您实际上并没有实现我提出的解决方案。其次,封闭的 div 的宽度为 120px,与图像的宽度大致相同,因此很难看出它是否真的居中图像。这是我的解决方案:jsfiddle.net/marvo/3k3CC/2
    【解决方案6】:

    .document {
      align-items: center;
      background-color: hsl(229, 57%, 11%);
      border-radius: 5px;
      display: flex;
      height: 40px;
      width: 40px;
    }
    
    .document img {
      display: block;
      margin: auto;
    }
    <div class="document">
      <img src="./images/icon-document.svg" alt="icon-document" />
    </div>

    【讨论】:

    • 欢迎来到stackoverflow!请为您的答案添加一些解释。
    【解决方案7】:

    使图像居中的响应方式可以是这样的:

    .center {
        display: block;
        margin: auto;
        max-width: 100%;
        max-height: 100%;
    }
    

    【讨论】:

      【解决方案8】:

      CSS flexbox 可以在图像父元素上使用 justify-content: center 来实现。要保留图像的纵横比,请将align-self: flex-start; 添加到其中。

      HTML

      <div class="image-container">
        <img src="http://placehold.it/100x100" />
      </div>
      

      CSS

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

      输出:

      body {
        background: lightgray;
      }
      .image-container {
        width: 200px;
        display: flex;
        justify-content: center;
        margin: 10px;
        padding: 10px;
        /* Material design properties */
        background: #fff;
        box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 3px 1px -2px rgba(0, 0, 0, 0.2), 0 1px 5px 0 rgba(0, 0, 0, 0.12);
      }
      .image-2 {
        width: 500px;
        align-self: flex-start;  /* to preserve image aspect ratio */
      }
      .image-3 {
        width: 300px;
        align-self: flex-start;  /* to preserve image aspect ratio */
      }
      <div class="image-container">
        <img src="http://placehold.it/100x100" />
      </div>
      
      <div class="image-container image-2">
        <img src="http://placehold.it/100x100/333" />
      </div>
      
      <div class="image-container image-3">
        <img src="http://placehold.it/100x100/666" />
      </div>

      【讨论】:

      • 浏览器支持这一点的优秀解决方案,我的支持。也可以使用align-items 垂直居中。各种边距解决方案对我不起作用,因为要居中的元素没有宽度和高度属性。
      • 在我的例子中,div 有一个给定的大小(例如 50px),这会将图像拉伸到 50px。
      • @Max 在这种情况下,您可以像这样将align-self 应用于图像元素jsfiddle.net/3fgvkurd
      【解决方案9】:

      将此添加到您的 CSS 中:

      #artiststhumbnail a img {
         display: block;
         margin-left: auto;
         margin-right: auto;
      }
      

      只是引用一个子元素,在这种情况下是图像。

      【讨论】:

      • 这适用于您仍想访问上边距的情况,.. 优于 margin 0 auto
      【解决方案10】:

      这就是我最终做的:

      <div style="height: 600px">
         <img src="assets/zzzzz.png" alt="Error" style="max-width: 100%; 
              max-height: 100%; display:block; margin:auto;" />
      </div>
      

      这会将图像高度限制为 600 像素,并将水平居中(如果父级宽度较小,则调整大小)到父级容器,保持比例。

      【讨论】:

        【解决方案11】:

        要将图像水平居中,这样可以:

        <p style="text-align:center"><img src=""></p>
        

        【讨论】:

        • 是的,但是如果您打算将图像显示为块以防止其下方出现无聊的空白,那么这将不再起作用...
        【解决方案12】:

        为左右设置相同的像素填充:

        <div id="artiststhumbnail" style="padding-left:ypx;padding-right:ypx">
        

        【讨论】:

          【解决方案13】:

          我尝试了几种方法。但是这种方式对我来说非常有效

          <img src="~/images/btn.png" class="img-responsive" id="hide" style="display: block; margin-left: auto; margin-right: auto;" />
          

          【讨论】:

            【解决方案14】:
            ##Both Vertically and Horizontally center of the Page
            .box{
                width: 300px;
                height: 300px;
                background-color: #232532;
                position: fixed;
                top: 0;
                bottom: 0;
                left: 0;
                right: 0;
                margin: auto;
            }
            

            【讨论】:

            • 欢迎来到stackoverflow!请为您的答案添加一些解释。
            • 如果我们想为所有设备修复特定的&lt;div&gt; &lt;section&gt;页面的垂直和水平中心,只需使用此样式代码!!!!
            • 看起来这个答案属于另一个问题:)
            【解决方案15】:

            我发现(似乎适用于所有浏览器)水平居中图像或任何元素的最佳方法是创建一个 CSS 类并包含以下参数:

            CSS

            .center {
                position: relative;          /* where the next element will be automatically positioned */
                display: inline-block;       /* causes element width to shrink to fit content */
                left: 50%;                   /* moves left side of image/element to center of parent element */
                transform: translate(-50%);  /* centers image/element on "left: 50%" position */
            }
            

            然后您可以将您创建的 CSS 类应用到您的标签,如下所示:

            HTML

            <img class="center" src="image.jpg" />
            

            您还可以通过执行以下操作在元素中内联 CSS:

            <img style="position: relative; display: inline-block; left: 50%; transform: translate(-50%);" src ="image.jpg" />
            

            ...但我不建议内联编写 CSS,因为如果您想更改样式,则必须使用居中的 CSS 代码对所有标签进行多次更改。

            【讨论】:

            • 完成了这项工作,但为了浏览器兼容性,您需要使用其他形式的转换。
            • 我还发现这个link 很有帮助。它显示了您在此处显示的类似transform: translate(-50%) 技巧,但将其与margin-left: 50% 结合使用,而不是left:50%。它还对比了项目何时具有`relative` 与absolute 定位的解决方案。这主要是为了我将来的参考,所以我可以在这里参考你的答案,以及我以前使用的解决方案,在 1(upvoted)位置。 :-) css-tricks.com/centering-css-complete-guide
            • 哦,这是我发现的另一个关于使用 transform: translate 技巧在元素和容器上定位的消息 [at w3.org] (w3.org/Style/Examples/007/center.en.html):基本规则是:1) 使 容器 relatively 定位,它声明它是绝对定位元素的容器。 2) 使 元素 本身 @987654333 @ly 定位。 3) 将其放置在容器的中间,使用“顶部:50%”(或水平放置 left:50%)。 4) 使用translation 将元素向上移动一半高度(或水平移动一半宽度)。
            【解决方案16】:

            我刚刚在 W3 CSS 页面上找到了这个解决方案,它回答了我的问题。

            img {
                display: block;
                margin-left: auto;
                margin-right: auto;
            }
            

            来源:http://www.w3.org/Style/Examples/007/center.en.html

            【讨论】:

            • 如果屏幕小于图像,我使用max-width: 100%; max-height: 100%; 调整图像大小,但在这种情况下它没有居中。关于如何以应用这两个属性为中心的任何建议
            【解决方案17】:

            在 div 中居中图像

            /* standar */
            div, .flexbox-div {
              position: relative;
              width: 100%;
              height: 100px;
              margin: 10px;
              background-color: grey;  
            }
            
            img {
              border: 3px solid red;
              width: 75px;
              height: 75px;
            }
            /* || standar */
            
            
            /* transform */
            .transform {
              position: absolute;
              top: 50%;
              left: 50%;
              transform: translate(-50%, -50%);
              -ms-transform: translate(-50%, -50%); /* IE 9 */
              -webkit-transform: translate(-50%, -50%); /* Chrome, Safari, Opera */ 
            }
            /* || transform */
            
            
            /* flexbox margin */
            .flexbox-div {
              display: -webkit-flex;
              display: flex;
              background-color: lightgrey; 
            }
            
            .margin-img {
              margin: auto;
            }
            /* || flexbox margin */
            
            
            /* flexbox justify align */
            .flexbox-justify {
              justify-content: center;
            }
            
            .align-item {
              align-self: center;
            }
            /* || flexbox justify align */
            <h4>Using transform </h4>  
            <div>
              <img class="transform" src="http://placeholders.org/250/000/fff" alt="Not By Design" border="1" />
            </div>
            
            <h4>Using flexbox margin</h4>  
            <div class="flexbox-div">
              <img class="margin-img" src="http://placeholders.org/250/000/fff" alt="Not By Design" border="1" />
            </div>
            
            <h4>Using flexbox justify align</h4>  
            <div class="flexbox-div flexbox-justify">
              <img class="align-item" src="http://placeholders.org/250/000/fff" alt="Not By Design" border="1" />
            </div>

            【讨论】:

              【解决方案18】:

              如果您必须内联执行此操作(例如使用输入框时),
              这是一个对我有用的快速技巧:围绕您的(在这种情况下为图片链接)
              divstyle="text-align:center"

              <div style="text-align:center">
              
              <a title="Example Image: Google Logo" href="https://www.google.com/" 
              target="_blank" rel="noopener"><img src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" alt="Google Logo. Click to visit Google.com" border="0" data-recalc-dims="1" /></a>
              
              <h6><strong>This text will also be centered </strong></h6>
              
              </div> /* ends centering style */
              

              【讨论】:

                【解决方案19】:

                您可以使用最少代码的弹性框对齐您的内容

                HTML

                <div class="image-container">
                <img src="https://image.freepik.com/free-vector/modern-abstract-background_1048-1003.jpg" width="100px"> 
                </div>
                

                CSS

                .image-container{
                  width:100%;
                  background:green;
                  display:flex;
                

                .image-container{
                  width:100%;
                  background:green;
                  display:flex;
                  justify-content: center;
                  align-items:center;
                }
                <div class="image-container">
                <img src="https://image.freepik.com/free-vector/modern-abstract-background_1048-1003.jpg" width="100px"> 
                </div>

                js小提琴链接https://jsfiddle.net/7un6ku2m/

                【讨论】:

                  【解决方案20】:
                  <!DOCTYPE html>
                  <html>
                      <head>
                          <meta charset="utf-8">
                          <meta name="viewport" content="width=device-width, initial-scale=1">
                  
                  
                        <style>
                        body{
                    /*-------------------important for fluid images---\/--*/
                    overflow-x: hidden; /* some browsers shows it for mysterious reasons to me*/
                    overflow-y: scroll;
                    margin-left:0px;
                    margin-top:0px;
                    /*-------------------important for fluid images---/\--*/
                        }
                        .thirddiv{
                        float:left;
                        width:100vw;
                        height:100vh;
                        margin:0px;
                        background:olive;
                        }
                        .thirdclassclassone{
                        float:left;   /*important*/
                        background:grey;
                        width:80vw;
                        height:80vh; /*match with img height bellow*/
                        margin-left:10vw; /* 100vw minus "width"/2    */
                        margin-right:10vw; /* 100vw minus "width"/2   */
                        margin-top:10vh;
                        }
                        .thirdclassclassone img{
                        position:relative; /*important*/
                       display: block;  /*important*/
                      margin-left: auto;  /*very important*/
                      margin-right: auto;  /*very important*/
                      height:80vh; /*match with parent div above*/
                  
                      /*--------------------------------
                      margin-top:5vh;
                      margin-bottom:5vh;
                      ---------------------------------*/
                      /*---------------------set margins to match total  height of parent di----------------------------------------*/
                        }
                      </style>           
                  </head>  
                  <body>
                      <div class="thirddiv">
                         <div class="thirdclassclassone">
                         <img src="ireland.png">
                      </div>      
                  </body>
                  </html>
                  

                  【讨论】:

                    【解决方案21】:

                    使用定位。以下对我有用...(水平和垂直居中)

                    缩放到图像中心(图像填充 div):

                    div{
                        display:block;
                        overflow:hidden;
                        width: 70px; 
                        height: 70px;  
                        position: relative;
                    }
                    div img{
                        min-width: 70px; 
                        min-height: 70px;
                        max-width: 250%; 
                        max-height: 250%;    
                        top: -50%;
                        left: -50%;
                        bottom: -50%;
                        right: -50%;
                        position: absolute;
                    }
                    

                    不缩放到图像的中心(图像填充 div):

                       div{
                            display:block;
                            overflow:hidden;
                            width: 100px; 
                            height: 100px;  
                            position: relative;
                        }
                        div img{
                            width: 70px; 
                            height: 70px; 
                            top: 50%;
                            left: 50%;
                            bottom: 50%;
                            right: 50%;
                            position: absolute;
                        }
                    

                    【讨论】:

                      【解决方案22】:

                      将图片放入newDiv。 使包含div 的宽度与图像相同。 将margin: 0 auto; 应用于newDiv。 这应该将 div 在容器内居中。

                      【讨论】:

                        【解决方案23】:

                        我要冒昧地说,以下就是你所追求的。

                        请注意,我认为问题中意外省略了以下内容(请参阅评论):

                        <div id="thumbnailwrapper"> <!-- <<< This opening element -->
                            <div id="artiststhumbnail">
                        ...
                        

                        所以你需要的是:

                        #artiststhumbnail {
                            width:120px;
                            height:108px;
                            margin: 0 auto; /* <<< This line here. */
                            ...
                        }
                        

                        http://jsfiddle.net/userdude/XStjX/3/

                        【讨论】:

                        • 嗯...我敢打赌这行得通。我在我的解决方案中将 IMAGE 居中,但我可以看到如何将问题解释为将 div-enclosure-the-image 居中在另一个 div 中。无论哪种方式,相同的解决方案。
                        • 这两种解决方案在实践中都不起作用。在它不起作用之前,我已经尝试了这两种解决方案。请参考问题中的编辑
                        猜你喜欢
                        • 1970-01-01
                        • 2012-04-16
                        • 1970-01-01
                        • 2012-11-26
                        • 2012-06-04
                        • 2017-02-26
                        • 1970-01-01
                        • 1970-01-01
                        • 2020-09-16
                        相关资源
                        最近更新 更多