【问题标题】:How to center a "position: absolute" element如何使“位置:绝对”元素居中
【发布时间】:2012-01-20 10:50:10
【问题描述】:

我在将属性position 设置为absolute 的元素居中时遇到问题。 有谁知道为什么图片不居中?

body {
  text-align: center;
}

#slideshowWrapper {
  margin-top: 50px;
  text-align: center;
}

ul#slideshow {
  list-style: none;
  position: relative;
  margin: auto;
}

ul#slideshow li {
  position: absolute;
}

ul#slideshow li img {
  border: 1px solid #ccc;
  padding: 4px;
  height: 450px;
}
<body>
  <div id="slideshowWrapper">
    <ul id="slideshow">
      <li><img src="https://source.unsplash.com/random/300*300?technology" alt="Dummy 1" /></li>
      <li><img src="https://source.unsplash.com/random/301*301?technology" alt="Dummy 2" /></li>
    </ul>
  </div>
</body>

【问题讨论】:

  • 你需要给 ul#slideshow 一个固定的宽度...

标签: html css css-position centering


【解决方案1】:

absolutely 定位的对象居中在 CSS 中相当复杂。

ul#slideshow li {
    position: absolute;
    left:50%;
    margin-left:-20px;

}

margin-left 更改为(负)要居中的元素宽度的一半。

【讨论】:

  • 在测试时,当图像尺寸不同时它不起作用,并且它们仍然相互堆叠
  • 太 hack-ish(因为它几乎总是用 css 证明)。但是太棒了! :-)
  • 我被其他一些聪明的答案所吸引,但只有这一个对我来说是可靠的。
  • 我遇到了和 Ryan 一样的问题,所以我尝试了“baaroz”建议的第二个答案,它对我有用!!!它也支持不同的分辨率,因为我的主要 DIV 的宽度为 % 而不是 PX
  • @Artsicle 那是因为所需的偏移量不是 20px --- left: calc(50% - Wpx/2) from my answer 工作,但需要知道宽度 - 此时原始CSS 本来可以工作的。
【解决方案2】:

绝对位置将其从流中取出,并将其放置在父级的 0x0 处(最后一个块元素具有绝对位置或相对位置)。

我不确定你到底想要完成什么,最好将 li 设置为 position:relative ,这将使它们居中。鉴于您当前的 CSS

查看http://jsfiddle.net/rtgibbons/ejRTU/ 来玩它

【讨论】:

  • :/ 最后的解决方案与您的几乎相同...
【解决方案3】:

要使一个 position:absolute 属性居中,您需要设置 left:50% 和 margin-left: -50% 的宽度。

<!-- for horizontal -->
<style>
div.center{
 width:200px;
 left:50%;
 margin-left:-100px;
 position:absolute;
}
</style>


<body>
 <div class='center'>
  should be centered horizontaly
 </div>
</body>

对于垂直中心绝对值,您需要做同样的事情,而不是左上角。 (注意:html 和 body 的最小高度必须为 100%;)

<!-- for vertical -->
<style>
 body,html{
  min-height:100%;
 }
 div.center{
  height:200px;
  top:50%;
  margin-top:-100px;
  position:absolute;
 }
</style>

<body>
 <div class='center'>
  should be centered verticaly
 </div>
</body>

两者都可以合并

   <!-- for both -->
 <style>
 body,html{
  min-height:100%;
 }
 div.center{
  width:200px;
  height:50px
  left:50%;
  top:50%;
  margin-left:-100px;
  margin-top:-25px;
  position:absolute;
 }
</style>


<body>
 <div class='center'>
  should be centered
 </div>
</body>

【讨论】:

    【解决方案4】:

    相对对象中的绝对对象是相对于其父对象的,这里的问题是您需要容器 #slideshowWrapper 的静态宽度,其余的解决方案就像其他用户所说的那样

    body {
        text-align: center;
    }
    
    #slideshowWrapper {
        margin-top: 50px;
        text-align:center;
        width: 500px;
    }
    
    ul#slideshow {
        list-style: none;
        position: relative;
        margin: auto;
    }
    
    ul#slideshow li {
        position: relative;
        left: 50%;
    }
    
    ul#slideshow li img {
        border: 1px solid #ccc;
        padding: 4px;
        height: 450px;
    }
    

    http://jsfiddle.net/ejRTU/10/

    【讨论】:

    • 两张图片相互叠加的小提琴。
    【解决方案5】:

    一个简单的 CSS 技巧,只需添加:

    width: 100%;
    text-align: center;
    

    这适用于图像和文本。

    【讨论】:

      【解决方案6】:

      使用margin-left: x%;,其中 x 是元素宽度的一半。

      【讨论】:

        【解决方案7】:

        如果你设置了宽度,你可以使用:

        position: absolute;
        margin-left: auto;
        margin-right: auto;
        left: 0;
        right: 0;
        text-align: center;
        

        【讨论】:

        • 这是一个比其他答案更清晰的答案!有什么注意事项吗?
        • 最聪明的答案。我刚刚检查过它,它适用于所有浏览器。它不适用于 IE8,但它适用于 IE>=9
        • 请务必在 IE 中测试,如果元素在 IE9 中设置了“最大宽度”,则此技巧不起作用
        • 我个人更喜欢语法“margin: 0 auto; left: 0; right: 0;”
        • 这根本行不通,除非设置了宽度。如果您在父元素上有 text-align:center 并且在绝对定位元素上没有背景,它可能会起作用,但是在其上放置背景,您会看到它实际上占据了整个宽度。 translateX(-50%) 答案是正确的。
        【解决方案8】:

        您的图片未居中,因为您的列表项未居中;只有他们的文本居中。您可以通过将整个列表居中或将列表中的图像居中来实现所需的定位。

        您的代码的修订版本可以在底部找到。在我的修订中,我将列表和其中的图像居中。

        事实上,您不能居中位置设置为绝对位置的元素。

        但是这种行为是可以模仿的!

        注意:这些说明适用于任何 DOM 块元素,而不仅仅是 img。

        1. 用 div 或其他标签(在您的情况下为 li)围绕您的图像。

          <div class="absolute-div">
            <img alt="my-image" src="#">
          </div>
          

          注意:这些元素的名称并不特殊。

        2. 改变你的 css 或 scss 给 div 绝对定位和你的图像居中。

          .absolute-div {
            position: absolute;
          
            width: 100%; 
            // Range to be centered over. 
          
            // If this element's parent is the body then 100% = the window's width
          
            // Note: You can apply additional top/bottom and left/right attributes
            // i.e. - top: 200px; left: 200px;
          
            // Test for desired positioning.
          }
          
          .absolute-div img {
            width: 500px;
            // Note: Setting a width is crucial for margin: auto to work.
          
            margin: 0 auto;
          }
          

        你有它!你的 img 应该居中!

        您的代码:

        试试这个:

        body
        {
          text-align : center;
        }
        
        #slideshow
        {
          list-style : none;
          width      : 800px;
          // alter to taste
        
          margin     : 50px auto 0;
        }
        
        #slideshow li
        {
          position : absolute;
        }
        
        #slideshow img
        {
          border  : 1px solid #CCC;
          padding : 4px;
          height  : 500px;
          width   : auto;
          // This sets the width relative to your set height.
        
          // Setting a width is required for the margin auto attribute below. 
        
          margin  : 0 auto;
        }
        <ul id="slideshow">
            <li><img src="http://lorempixel.com/500/500/nature/" alt="Dummy 1" /></li>
            <li><img src="http://lorempixel.com/500/500/nature/" alt="Dummy 2" /></li>
        </ul>

        我希望这会有所帮助。祝你好运!

        【讨论】:

          【解决方案9】:

          Div 垂直和水平居中对齐

          top: 0;
          bottom: 0;
          margin: auto;
          position: absolute;
          left: 0;
          right: 0;
          

          注意:元素应该有宽度和高度要设置

          【讨论】:

          • 我不知道为什么这没有得到更多的投票。据我所知,适用于所有浏览器,包括移动浏览器。接缝在支撑方面更可靠。它简单、容易、干净……
          • 这是一个更好的答案。它只需要一个 div 来制作,并且比调用 left:50%;, top:50%; 有更多的用例。喜欢 69+ 票的解决方案
          • 目前为止最好的答案,任何来这里的人都应该检查一下!
          • 该元素还需要一个height 设置才能工作。
          • 这太完美了!此外,只需添加height: fit-contentwidth: fit-content 即可根据其元素调整大小
          【解决方案10】:

          越简单越好:

          img {
                      top: 0;
                      bottom: 0;
                      left: 0;
                      right: 0;
                      margin: auto auto;
                      position: absolute;
          }
          

          然后你需要将你的img标签插入一个带有position:relative属性的标签中,如下:

          <div style="width:256px; height: 256px; position:relative;">
                <img src="photo.jpg"/>
          </div>
          

          【讨论】:

            【解决方案11】:
                <div class="centered_content"> content </div>
                <style type="text/css">
                .centered_content {
                   text-align: center;
                   position: absolute;
                   left: 0;
                   right: 0;
                }
                </style>
            

            查看演示:http://jsfiddle.net/MohammadDayeh/HrZLC/

            text-align: center;在添加 left: 0; right: 0; 时使用 position: absolute 元素

            【讨论】:

            • 请提供一些评论或解释为什么此代码有效。代码答案本身将不可避免地被标记为删除。
            【解决方案12】:

            如果你想让一个绝对元素居中

            #div {
                position:absolute;
                top:0;
                bottom:0;
                left:0;
                right:0;
                width:300px; /* Assign a value */
                height:500px; /* Assign a value */
                margin:auto;
            }
            

            如果您希望容器从左到右居中,而不是从上到下

            #div {
                position:absolute;
                left:0;
                right:0;
                width:300px; /* Assign a value */
                height:500px; /* Assign a value */
                margin:auto;
            }
            

            如果您希望容器从上到下居中,而不考虑从左到右

            #div {
                position:absolute;
                top:0;
                bottom:0;
                width:300px; /* Assign a value */
                height:500px; /* Assign a value */
                margin:auto;
            }
            

            2015 年 12 月 15 日更新

            几个月前我学到了另一个新技巧。假设你有一个相对的父元素。

            这是你的绝对元素。

            .absolute-element { 
                position:absolute; 
                top:50%; 
                left:50%; 
                transform:translate(-50%, -50%); 
                width:50%; /* You can specify ANY width values here */ 
            }
            

            有了这个,我认为它比我的旧解决方案更好。因为您不必指定宽度和高度。这个它适应元素本身的内容。

            2021 年 4 月 23 日更新

            它不回答 OP 关于绝对位置的问题,但如果您想要替代解决方案,则称为 flexbox。这是一个例子。

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

            它的作用是将容器转换为flex,并使用justify-content:center 将子项对齐到水平中心,垂直对齐使用align-items:center。它也支持现代浏览器,因此使用起来很安全。

            不过,请务必先阅读 flexbox 的工作原理。

            https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Flexbox

            Flexbox 支持的浏览器

            https://caniuse.com/flexbox

            【讨论】:

            • 使用 flexbox 为我解决了这个问题
            【解决方案13】:

            似乎正在发生的是有两种解决方案;使用边距居中,使用位置居中。两者都工作正常,但是如果你想相对于这个居中的元素对一个元素进行绝对定位,你需要使用绝对位置方法,因为第二个元素的绝对位置默认为定位的第一个父元素。像这样:

            <!-- CENTERED USING MARGIN -->
            <div style="width:300px; height:100px; border: 1px solid #000; margin:20px auto; text- align:center;">
                <p style="line-height:4;">width: 300 px; margin: 0 auto</p>
                <div style="position:absolute; width:100px; height:100px; background-color:#ff0000; top:-20px; left:0px;">
                    <p style="line-height:4;">Absolute</p>
                </div>
            </div>
            
            <!-- CENTERED USING POSITION -->
            <div style="position:absolute; left:50%; width:300px; height:100px; border: 1px solid #000; margin:20px 0 20px -150px; text-align:center;">
                <p style="line-height:2;">width:300px; position: absolute; left: 50%; margin-left:-150px;</p>
                <div style="position:absolute; width:100px; height:100px; background-color:#ff0000; top:0px; left:-105px;">
                    <p style="line-height:4;">Absolute</p>
                </div>
            </div>
            

            在我阅读这篇文章之前,使用 margin:0 自动技术在我的内容左侧构建一个菜单,我必须在右侧构建一个相同宽度的列来平衡它。不漂亮。谢谢!

            【讨论】:

              【解决方案14】:

              在不知道定位1元素的width/height的情况下,仍然可以如下对齐:

              EXAMPLE HERE

              .child {
                  position: absolute;
                  top: 50%;  /* position the top  edge of the element at the middle of the parent */
                  left: 50%; /* position the left edge of the element at the middle of the parent */
              
                  transform: translate(-50%, -50%); /* This is a shorthand of
                                                       translateX(-50%) and translateY(-50%) */
              }
              

              值得注意的是CSS Transformis supported in IE9 and above(为简洁起见,省略了供应商前缀)


              说明

              添加top/left50% 将元素的上/左边缘移动到父元素的中间,并且translate() 函数具有(负)-50% 将元素移动其大小的一半。因此元素将位于中间。

              这是因为top/left 属性上的百分比值是相对于父元素(正在创建包含块)的高度/宽度。

              虽然translate()transform函数上的百分比值是相对于元素本身的宽度/高度(实际上是指bounding box的大小)

              对于单向对齐,请改用translateX(-50%)translateY(-50%)


              1.具有position 而非static 的元素。 IE。 relativeabsolutefixed 值。

              【讨论】:

              • 这应该是最佳答案!!
              • 太棒了!最好的!
              • 我到处寻找答案和一个很好的解释。这是最好的答案,也是一个很好的解释!谢谢。
              • 水平居中:position: absolute; left: 50%; transform: translateX(-50%);,垂直居中:position: absolute; top: 50%; transform: translateY(-50%);
              • 刚刚发现translate属性,将元素翻译成自身的大小,不管其父元素的大小。
              【解决方案15】:

              如果您不知道元素的宽度,可以使用以下代码:

              <body>
              <div style="position: absolute; left: 50%;">
                  <div style="position: relative; left: -50%; border: dotted red 1px;">
                      I am some centered shrink-to-fit content! <br />
                      tum te tum
                  </div>
              </div>
              

              小提琴演示:http://jsfiddle.net/wrh7a21r/

              来源:https://stackoverflow.com/a/1777282/1136132

              【讨论】:

              • @NabiK.A.Z.如果您不知道元素的宽度,此示例很有用。在您的示例中,您为 div 设置了宽度。
              【解决方案16】:
              #parent
              {
                  position : relative;
                  height: 0;
                  overflow: hidden;
                  padding-bottom: 56.25% /* images with aspect ratio: 16:9  */
              }
              
              img 
              {
                  height: auto!important;
                  width: auto!important;
                  min-height: 100%;
                  min-width: 100%;
                  position: absolute;
                  display: block;
                  /*  */
                  top: -9999px;
                  bottom: -9999px;
                  left: -9999px;
                  right: -9999px;
                  margin: auto;
              }
              

              我不记得我在哪里看到上面列出的居中方法,使用负的上、右、下、左值。 对我来说,这种技术在大多数情况下都是最好的。

              当我使用上面的组合时,图像的行为类似于具有以下设置的背景图像:

              background-position: 50% 50%;
              background-repeat: no-repeat;
              background-size: cover;
              

              关于第一个例子的更多细节可以在这里找到:
              Maintain the aspect ratio of a div with CSS

              【讨论】:

                【解决方案17】:

                我不确定您想要完成什么,但在这种情况下,只需将 width: 100%; 添加到您的 ul#slideshow li 即可。

                说明

                img 标签是内联块元素。这意味着它们像文本一样内联流动,但也像块元素一样具有宽度和高度。在您的 css 中有两个 text-align: center; 规则应用于 &lt;body&gt;#slideshowWrapper (这是多余的顺便说一句)这使得所有内联和内联块子元素都集中在它们最接近的块元素中,在您的代码中这些是li 标签。所有块元素都有width: 100%,如果它们是静态流(position: static;),这是默认的。问题是当你告诉li标签是position: absolute;时,你把它们从正常的静态流中取出,这导致它们缩小它们的大小以适应它们的内部内容,换句话说,它们有点“丢失”他们的width: 100% 属性。

                【讨论】:

                  【解决方案18】:

                  使用 left: calc(50% - Wpx/2); 其中 W 是元素的宽度,对我有用。

                  【讨论】:

                  • 你如何确定 W?
                  • 他说的是“图像”——理想情况下,在为网络制作图像时,您应该将图像制作成您将要使用的大小(而不是调整大小)以避免不必要的重量(如果你把大图像变小)或模糊性(如果你把小图像变大)。 - 如果您使用 jQuery,您可以使用“imageElement.naturalHeight”和“imageElement.naturalWidth”,然后也可以动态设置样式,但这有点复杂。公平地说,许多其他答案还需要您知道图像的宽度才能使他们的技术发挥作用。
                  • 如果您实际上不清楚如何获取 W,在 Chrome 中您可以使用 CTRL+Shift+i(开发人员工具),然后使用 CTRL+Shift+C(检查模式)将鼠标悬停在元素上并看看事情有多宽。你也可以决定你想要它有多宽,然后在你的 CSS 中添加“width: Wpx”。
                  【解决方案19】:

                  这里是使用“位置:绝对”的中心元素的简单和最佳解决方案

                   body,html{
                    min-height:100%;
                   }
                   
                   div.center{
                   width:200px;
                   left:50%;
                   margin-left:-100px;/*this is 50% value for width of the element*/
                   position:absolute;
                   background:#ddd;
                   border:1px solid #999;
                   height:100px;
                   text-align:center
                   }
                   
                   
                  <style>
                  
                  </style>
                  
                  <body>
                   <div class='center'>
                    should be centered verticaly
                   </div>
                  </body>

                  【讨论】:

                    【解决方案20】:

                    这对我有用:

                    position: absolute;
                    left: 50%;
                    transform: translateX(-50%);
                    

                    【讨论】:

                      【解决方案21】:

                      html, body, ul, li, img {
                        box-sizing: border-box;
                        margin: 0px;  
                        padding: 0px;  
                      }
                      
                      #slideshowWrapper {
                        width: 25rem;
                        height: auto;
                        position: relative;
                        
                        margin-top: 50px;
                        border: 3px solid black;
                      }
                      
                      ul {
                        list-style: none;
                        border: 3px solid blue;  
                      }
                      
                      li {
                        /* center horizontal */
                        position: relative;
                        left: 0;
                        top: 50%;
                        width: 100%;
                        text-align: center;
                        font-size: 18px;
                        /* center horizontal */
                        
                        border: 3px solid red; 
                      }
                      
                      img {
                        border: 1px solid #ccc;
                        padding: 4px;
                        //width: 200px;
                        height: 100px;
                      }
                      <body>
                        <div id="slideshowWrapper">
                          <ul id="slideshow">
                            <li><img src="http://via.placeholder.com/350x150" alt="Dummy 1" /></li>
                            <li><img src="http://via.placeholder.com/140x100" alt="Dummy 2" /></li>
                            <li><img src="http://via.placeholder.com/200x100" alt="Dummy 3" /></li>      
                          </ul>
                        </div>
                      </body>

                      【讨论】:

                      • 这个答案只有代码。虽然它可能是正确的,但它应该附带解释为什么代码回答了 OP 的问题。 Stack Exchnge 上的代码不是“自我解释的”。
                      【解决方案22】:

                      你可以试试这个方法:

                      * { margin: 0px; padding: 0px; }
                      #body { height: 100vh; width: 100vw; position: relative; 
                              text-align: center; 
                              background-image: url('https://s-media-cache-ak0.pinimg.com/originals/96/2d/ff/962dff2247ad680c542622e20f44a645.jpg'); 
                               background-size: cover; background-repeat: no-repeat; }
                      .text { position: absolute; top: 0; bottom: 0; left: 0; right: 0; height:100px; 
                              display: inline-block; margin: auto; z-index: 999999; }
                      <html>
                      <body>
                      	<div id="body" class="container-fluid">
                      	  <!--Background-->
                      	    <!--Text-->
                      		  <div class="text">
                      		    <p>Random</p>
                      		  </div>	  
                      	</div>
                      </body>
                      </html>

                      【讨论】:

                        【解决方案23】:

                        将“位置:绝对”元素居中。

                        .your-element {
                          position: absolute;
                          left: 0;
                          right: 0;
                          text-align: center; // or this ->  margin: 0 auto;
                        }
                        

                        【讨论】:

                        • 这是最好的解决方案。将左右设置为 0。
                        【解决方案24】:

                        可能是最短的

                        position:absolute;
                        left:0;right:0;top:0;bottom:0;
                        margin:0 auto;
                        

                        【讨论】:

                        • 这非常棒,但是为了垂直和水平居中,我们只需要自动设置边距
                        【解决方案25】:

                        或者你现在可以使用带有绝对位置的弹性框:

                        .parent {
                            position: relative;
                            display: flex;
                            justify-content: center;
                        }
                        
                        .child {
                            position: absolute;
                        }
                        

                        【讨论】:

                        • 这被低估了。
                        • 这仅在您想要对齐所有项目时才正确。如果你有更多,你想区分,那是行不通的。
                        【解决方案26】:

                        只需在父元素上使用display: flexjustify-content: center

                        body {
                            text-align: center;
                        }
                        
                        #slideshowWrapper {
                            margin-top: 50px;
                            text-align: center;
                        }
                        
                        ul#slideshow {
                            list-style: none;
                            position: relative;
                            margin: auto;
                            display: flex;
                            justify-content: center;
                        }
                        
                        ul#slideshow li {
                            position: absolute;
                        }
                        
                        ul#slideshow li img {
                            border: 1px solid #ccc;
                            padding: 4px;
                            height: 100px;
                        }
                        <body>
                           <div id="slideshowWrapper">
                              <ul id="slideshow">
                                 <li><img src="https://source.unsplash.com/random/300*300?technology" alt="Dummy 1" /></li>
                                 <li><img src="https://source.unsplash.com/random/301*301?technology" alt="Dummy 2" /></li>
                              </ul>
                           </div>
                        </body>
                        
                        <!-- Images from Unsplash-->

                        你可以在JSFIDDLE找到这个解决方案

                        【讨论】:

                          【解决方案27】:

                          1- 当你知道绝对定位元素的宽度时。

                          width: 200px;
                          position: absolute;
                          left: 50%;
                          margin-left: -100px
                          

                          2- 当你不知道绝对定位元素的宽度时。出色的响应能力,但 CSS3 较旧的浏览器可能会出现问题。

                          position: absolute;
                          left: 50%;
                          -webkit-transform: translateX(-50%);
                          transform: translateX(-50%)
                          

                          3- 当您不知道绝对定位元素的宽度,但将其设置为可能不适合设计的父元素的 100% 宽度时。

                          position: absolute;
                          left: 0;
                          right: 0;
                          margin: auto
                          

                          如果你知道宽度,你也可以使用第三个选项,它会居中。

                          【讨论】:

                            【解决方案28】:

                            我最喜欢的绝对居中任何元素或元素组的方法是绝对定位它们的容器,使其成为相对容器的高度和宽度,然后使用 flex 对齐其中的元素。

                            在这种特定情况下:

                            body {
                              position: relative; /* OPTIONAL */
                            }
                            
                            #slideshowWrapper {
                              position: absolute;
                              top: 0;
                              left: 0;
                              width: 100%;
                              height: 100%;
                              display: flex;
                              flex-direction: row; /* OPTIONAL IF ONLY ONE ELEMENT */
                              justify-content: center;
                              align-items: center;
                            }
                            
                            

                            希望有帮助,干杯。

                            【讨论】:

                              【解决方案29】:

                              你可以使用“transform”属性:

                              position: absolute;
                              top: 50%;
                              left: 50%;
                              -webkit-transform: translateX(-50%) translateY(-50%);
                              transform: translateX(-50%) translateY(-50%);
                              

                              【讨论】:

                                【解决方案30】:

                                对于这种情况,我认为下面的代码就足够了:

                                    ul#slideshow li {
                                      position: absolute;
                                      left: 0;
                                      right: 0;
                                    }
                                

                                【讨论】:

                                  猜你喜欢
                                  • 2020-10-08
                                  • 1970-01-01
                                  • 2017-02-01
                                  • 2013-10-21
                                  • 2022-12-02
                                  • 2014-03-05
                                  • 1970-01-01
                                  • 2019-07-01
                                  • 2012-08-22
                                  相关资源
                                  最近更新 更多