【问题标题】:Centering a div block without the width居中没有宽度的 div 块
【发布时间】:2010-09-21 23:43:29
【问题描述】:

当我尝试将 div 块“产品”居中时遇到问题,因为我事先不知道 div 宽度。有人有解决办法吗?

更新:我的问题是我不知道要显示多少产品,我可以有 1、2 或 3 个产品,如果它是固定数字,我可以将它们居中,因​​为我知道宽度父div的,我只是不知道当内容是动态的时候怎么做。

.product_container {
  text-align: center;
  height: 150px;
}

.products {
  height: 140px;
  text-align: center;
  margin: 0 auto;
  clear: ccc both; 
}
.price {
  margin: 6px 2px;
  width: 137px;
  color: #666;
  font-size: 14pt;
  font-style: normal;
  border: 1px solid #CCC;
  background-color:	#EFEFEF;
}
<div class="product_container">
  <div class="products" id="products">
    <div id="product_15">
      <img src="/images/ecommerce/card_default.png">
      <div class="price">R$ 0,01</div>
    </div>

    <div id="product_15">
      <img src="/images/ecommerce/card_default.png">
      <div class="price">R$ 0,01</div>
    </div>   

    <div id="product_15">
      <img src="/images/ecommerce/card_default.png">
      <div class="price">R$ 0,01</div>
    </div>
  </div>
</div>

【问题讨论】:

  • 您遇到的具体问题是什么?

标签: html css


【解决方案1】:

2015 年 2 月 27 日更新:我的原始答案不断获得支持,但现在我通常改用 @bobince 的方法。

.child { /* This is the item to center... */
  display: inline-block;
}
.parent { /* ...and this is its parent container. */
  text-align: center;
}

我出于历史目的的原始帖子:

您可能想尝试这种方法。

<div class="product_container">
    <div class="outer-center">
        <div class="product inner-center">
        </div>
    </div>
    <div class="clear"/>
</div>

下面是搭配风格:

.outer-center {
    float: right;
    right: 50%;
    position: relative;
}
.inner-center {
    float: right;
    right: -50%;
    position: relative;
}
.clear {
    clear: both;
}

JSFiddle

这里的想法是,您将要居中的内容包含在两个 div 中,一个外部 div 和一个内部 div。您浮动两个 div 以便它们的宽度自动缩小以适合您的内容。接下来,您将外部 div 与它的右边缘相对定位在容器的中心。最后,您将内部 div 相对方向定位为其自身宽度的一半(实际上是外部 div 的宽度,但它们是相同的)。最终将内容集中在它所在的任何容器中。

如果您依赖“产品”内容来调整“product_container”的高度,您可能最后需要那个空 div。

【讨论】:

  • 如果您不为.product_container 提供overflow:hidden,则outer-center div 将与其右侧的其他附近内容重叠。 outer-center 右侧的任何链接或按钮都不起作用。尝试outer-center 的背景颜色以了解overflow :hidden 的需求。 这是Cicil Thomas建议的编辑
  • 这种方法非常适合桌面网站......不过,在移动网站上,inner-divs 似乎附加在右侧。有解决办法吗?
  • 告诉我吧!有时我们只是需要一个解决方案,而没有选择一个好的解决方案的奢侈。单单元格表格是另一种选择,尽管只有一个单元格的表格并不是真正的表格,不是吗?
  • @fgysin 同意,这是一种反直觉的黑客行为。设计师想知道为什么人们仍然考虑退回到基于表格的布局。
  • 这个问题有五年了。这个答案已经过时了,但一开始就不是很优雅。你应该做的是使用 display:inline-block
【解决方案2】:

带有“display: block”的元素(默认为 div)的宽度由其容器的宽度决定。您不能使块的宽度取决于其内容的宽度(缩小以适应)。

(除了 CSS 2.1 中的“浮动:左/右”块,但这对居中没有用处。)

您可以将“display”属性设置为“inline-block”,以将块转换为可通过其父级的 text-align 属性控制的缩小以适应对象,但浏览器支持参差不齐。如果你想这样做,你可以通过使用 hacks(例如,参见 -moz-inline-stack)来摆脱它。

另一种方法是桌子。当您的列的宽度确实无法提前知道时,这可能是必要的。我无法从示例代码中真正看出您要做什么 - 那里没有明显的需要缩小以适应块 - 但是可以考虑产品列表表格。

[PS。切勿在网络上使用“pt”作为字体大小。如果你真的需要固定大小的文本,'px' 更可靠,否则像'%' 这样的相对单位更好。还有“clear: ccc both” — 错字?]

.center{
   text-align:center; 
}

.center > div{ /* N.B. child combinators don't work in IE6 or less */
   display:inline-block;
}

JSFiddle

【讨论】:

  • 父 -> 文本对齐:中心 | child-> display:inline-block
  • display: inline-block 在 IE7 和旧版本的 Firefox 中不受支持
  • @Jakobud,对于 IE7 使用“显示:内联;缩放:1;”而不是“显示:内联块;”。它适用于块元素。
  • 查看此链接以获取有关如何跨浏览器使用此方法的更多信息 - blog.mozilla.org/webdev/2009/02/20/cross-browser-inline-block
  • 我使用这个scss来实现它,只要你的html结构存在支持它就可以工作:.center { text-align: center; &:first-child { display: inline-block; } }
【解决方案3】:

大多数浏览器都支持display: table; CSS 规则。这是一个很好的技巧,可以在不添加额外 HTML 或将约束样式应用到容器的情况下将容器中的 div 居中(例如 text-align: center;,它将使容器中的所有其他内联内容居中),同时保持包含的 div 的动态宽度:

HTML:

<div class="container">
  <div class="centered">This content is centered</div>
</div>

CSS:

.centered { display: table; margin: 0 auto; }

.container {
  background-color: green;
}
.centered {
  display: table;
  margin: 0 auto;
  background-color: red;
}
<div class="container">
  <div class="centered">This content is centered</div>
</div>

更新(2015-03-09):

今天正确的做法是使用 flexbox 规则。浏览器支持有点受限(CSS table support vs flexbox support),但这种方法还允许做很多其他事情,并且是针对此类行为的专用 CSS 规则:

HTML:

<div class="container">
  <div class="centered">This content is centered</div>
</div>

CSS:

.container {
  display: flex;
  flex-direction: column; /* put this if you want to stack elements vertically */
}
.centered { margin: 0 auto; }

.container {
  display: flex;
  flex-direction: column; /* put this if you want to stack elements vertically */
  background-color: green;
}
.centered {
  margin: 0 auto;
  background-color: red;
}
<div class="container">
  <div class="centered">This content is centered</div>
</div>

【讨论】:

  • 我认为这绝对是最好的解决方案。不涉及任何带有浮动嵌套 div 或类似内容的奇怪技巧。我认为它没有被评为更高的唯一原因是人们对桌子太过分了。这不是表格,所以我认为这是一种完全合法的方法。
  • 同意,这似乎是最好的解决方案。虽然@bobince 的解决方案也很简单,但它具有改变内部元素样式的副作用。
  • display: table; 变体非常适合伪元素(::before::after),在这种情况下,您无法添加额外的标记,并且希望避免破坏相邻元素样式。跨度>
【解决方案4】:

给猫剥皮的六种方法:

按钮一display: block 类型的任何内容都将采用父项的完整宽度。 (除非与 floatdisplay: flex 父级结合使用)。真的。不好的例子。

按钮 2: 选择 display: inline-block 将导致自动(而不是全)宽度。然后,您可以在包装块上使用text-align: center 居中可能是最简单、最广泛兼容的,即使是“老式”浏览器...

.wrapTwo
  text-align: center;
.two
  display: inline-block; // instantly shrinks width

按钮 3: 无需在包装上放任何东西。所以也许这是最优雅的解决方案。也可以垂直工作。 (现在浏览器对翻译的支持是good enough (≥IE9)...)。

position: relative;
display: inline-block; // instantly shrinks width
left: 50%;
transform: translateX(-50%);

顺便说一句:也是垂直居中未知高度的块的好方法(与绝对定位有关)。

按钮 4: 绝对定位。只要确保在包装器中保留足够的高度,因为没有其他人会(无论是 clearfix 还是隐式...)

.four
  position absolute
  top 0
  left 50%
  transform translateX(-50%)
.wrapFour
  position relative // otherwise, absolute positioning will be relative to page!
  height 50px // ensure height
  background lightgreen // just a marker

按钮 5: 浮动(也将块级元素带入动态宽度)和相对移位。虽然我从未在野外见过这个。或许有缺点……

.wrapFive
  &:after // aka 'clearfix'
    content ''
    display table
    clear both

.five  
  float left
  position relative
  left 50%
  transform translateX(-50%)

更新: 按钮 6: 现在,你也可以使用 flex-box。请注意,样式适用于居中对象的包装。

.wrapSix
  display: flex
  justify-content: center

→ full source code (stylus syntax)

【讨论】:

    【解决方案5】:

    我找到了一个更优雅的解决方案,结合“inline-block”来避免使用 float 和 hacky clear:both。它仍然需要嵌套的 div,这不是很语义化,但它可以正常工作......

    div.outer{
        display:inline-block;
        position:relative;
        left:50%;
    }
    
    div.inner{
        position:relative;
        left:-50%;
    }
    

    希望对你有帮助!

    【讨论】:

      【解决方案6】:
      <div class="outer">
         <div class="target">
            <div class="filler">
            </div>
         </div>
      </div>
      
      .outer{
         width:100%;
         height: 100px;
      }
      
      .target{
         position: absolute;
         width: auto;
         height: 100px;
         left: 50%;
         transform: translateX(-50%);
      }
      
      .filler{
         position:relative;
         width:150px;
         height:20px;
      }
      

      如果目标元素是绝对定位的,您可以通过将其向一个方向移动 50% (left: 50%) 将其居中,然后将其向相反方向移动 50% (transform:translateX(-50%))。这无需定义目标元素的宽度(或width:auto)即可工作。父元素的位置可以是静态的、绝对的、相对的或固定的。

      【讨论】:

      • 这将偏离中心宽度的一半。
      • @4imble 不,不会的。 "left" 属性将其移动 50%(其父元素宽度的 50%), translateX(-50%) 将其向另一方向移动 50%(目标元素宽度的 50%)。
      • 啊,是的,我错过了 translateX。不确定这在 IE 11 之前的任何 IE 中是否可靠。但你是对的。
      【解决方案7】:

      默认情况下,div 元素显示为块元素,因此它们具有 100% 的宽度,使它们居中毫无意义。正如 Arief 所建议的,您必须指定 width,然后您可以在指定 margin 时使用 auto 以使 div 居中。

      或者,您也可以强制使用display: inline,但这样您的行为几乎就像span 而不是div,所以这没有多大意义。

      【讨论】:

        【解决方案8】:

        这将使一个元素居中,例如有序列表、无序列表或任何元素。 只需用类为outerElement 的Div 包装它,并为内部元素提供innerElement 类。

        outerelement 类用于 IE、旧 Mozilla 和大多数较新的浏览器。

         .outerElement {
                display: -moz-inline-stack;
                display: inline-block;
                vertical-align: middle;
                zoom: 1;
                position: relative;
                left: 50%;
            }
        
        .innerElement {
            position: relative;
            left: -50%;
        } 
        

        【讨论】:

        • 请在您的代码中添加描述。自己发布代码对 SO 的未来访问者来说意义不大。
        【解决方案9】:

        使用 css3 flexbox 和 justify-content:center;

            <div class="row">
                 <div class="col" style="background:red;">content1</div>
                  <div class="col" style="">content2</div>
            </div>
        
        
        .row {
            display: flex; /* equal height of the children */
            height:100px;
            border:1px solid red;
            width: 400px;
            justify-content:center;
        }
        

        【讨论】:

          【解决方案10】:

          Mike M. Lin's answer 略有不同

          如果将overflow: auto;(或hidden)添加到div.product_container,则不需要div.clear

          本文来源于这篇文章->http://www.quirksmode.org/css/clearing.html

          这里是修改后的 HTML:

          <div class="product_container">
              <div class="outer-center">
                  <div class="product inner-center">
                  </div>
              </div>
          </div>
          

          这里是修改后的 CSS:

          .product_container {
            overflow: auto;
            /* width property only required if you want to support IE6 */
            width: 100%;
          }
          
          .outer-center {
            float: right;
            right: 50%;
            position: relative;
          }
          
          .inner-center {
            float: right;
            right: -50%;
            position: relative;
          }
          

          原因,为什么没有div.clear 会更好(除了有一个空元素感觉不对)是 Firefox 过分热心的边距分配。

          例如,如果你有这个 html:

          <div class="product_container">
              <div class="outer-center">
                  <div class="product inner-center">
                  </div>
              </div>
              <div style="clear: both;"></div>
          </div>
          <p style="margin-top: 11px;">Some text</p>
          

          然后,在 Firefox(撰写本文时为 8.0)中,您将看到 11px 边距之前 product_container。更糟糕的是,即使内容非常适合屏幕尺寸,您也会获得整个页面的垂直滚动条。

          【讨论】:

            【解决方案11】:

            试试这个新的 CSS 和标记

            这里是修改后的 HTML:

            <div class="product_container">
            <div class="products" id="products">
               <div id="product_15" class="products_box">
                   <img src="/images/ecommerce/card_default.png">
                   <div class="price">R$ 0,01</div>
               </div>
               <div id="product_15" class="products_box">
                   <img src="/images/ecommerce/card_default.png">
                   <div class="price">R$ 0,01</div>
               </div>   
               <div id="product_15" class="products_box">
                   <img src="/images/ecommerce/card_default.png">
                   <div class="price">R$ 0,01</div>
               </div>
            </div>
            

            这里是修改后的 CSS:

            <pre>
            .product_container 
             {
             text-align:    center;
             height:        150px;
             }
            
            .products {
                left: 50%;
            height:35px;
            float:left;
            position: relative;
            margin: 0 auto;
            width:auto;
            }
            .products .products_box
            {
            width:auto;
            height:auto;
            float:left;
              right: 50%;
              position: relative;
            }
            .price {
                margin:        6px 2px;
                width:         137px;
                color:         #666;
                font-size:     14pt;
                font-style:    normal;
                border:        1px solid #CCC;
                background-color:   #EFEFEF;
            }
            

            【讨论】:

              【解决方案12】:
              <div class="product_container">
              <div class="outer-center">
              <div class="product inner-center">
                  </div>
              </div>
              <div class="clear"></div>
              </div>
              
              .outer-center
              {
              float: right;
              right: 50%;
              position: relative;
              }
              .inner-center 
              {
              float: right;
              right: -50%;
              position: relative;
              }
              .clear 
              {
              clear: both;
              }
              
              .product_container
              {
              overflow:hidden;
              }
              

              如果您没有为“.product_container”提供“overflow:hidden”,则“outer-center”div 将与其右侧的其他附近内容重叠。 “外部中心”右侧的任何链接或按钮都不起作用。尝试“外中心”的背景颜色以了解“溢出:隐藏”的需要

              【讨论】:

                【解决方案13】:

                我找到了有趣的解决方案,我正在制作滑块并且必须居中滑动控件,我做到了并且工作正常。您还可以将相对位置添加到父级并垂直移动子级位置。看看http://jsfiddle.net/bergb/6DvJz/

                CSS:

                #parent{
                        width:600px;
                        height:400px;
                        background:#ffcc00;
                        text-align:center;
                    }
                
                #child{
                        display:inline-block;
                        margin:0 auto;
                        background:#fff;
                    }  
                

                HTML:

                <div id="parent">
                    <div id="child">voila</div>
                </div>
                

                【讨论】:

                  【解决方案14】:

                  执行display:table; 并将margin 设置为auto

                  重要的代码:

                  .relatedProducts {
                      display: table;
                      margin-left: auto;
                      margin-right: auto;
                  }
                  

                  无论你现在有多少元素,它都会自动居中对齐

                  代码 sn-p 中的示例:

                  .relatedProducts {
                      display: table;
                      margin-left: auto;
                      margin-right: auto;
                  }
                  a {
                    text-decoration:none;
                  }
                  <div class="row relatedProducts">
                  <div class="homeContentTitle" style="margin: 100px auto 35px; width: 250px">Similar Products</div>
                  					
                  <a href="#">test1 </a>
                  <a href="#">test2 </a>
                  <a href="#">test3 </a>
                  </div>

                  【讨论】:

                    【解决方案15】:

                    恐怕没有明确指定宽度的唯一方法是使用(喘气)表格。

                    【讨论】:

                    • 改述:如果您不想花下一个小时尝试各种 CSS、嵌套 DIV 和浏览器的组合,请直接转到表格。
                    • 表格并非旨在用作设计元素。那是糟糕的风格。
                    【解决方案16】:

                    糟糕的修复,但它确实有效......

                    CSS:

                    #mainContent {
                        position:absolute;
                        width:600px;
                        background:#FFFF99;
                    }
                    
                    #sidebar {
                        float:left;
                        margin-left:610px;
                        max-width:300;
                        background:#FFCCCC;
                    }
                    #sidebar{
                    
                    
                        text-align:center;
                    }
                    

                    HTML:

                    <center>
                    <table border="0" cellspacing="0">
                      <tr>
                        <td>
                    <div id="mainContent">
                    1<br/>
                    <br/>
                    123<br/>
                    123<br/>
                    123<br/>
                    </div><div id="sidebar"><br/>
                    </div></td>
                    </tr>
                    </table>
                    </center>
                    

                    【讨论】:

                      【解决方案17】:

                      适用于旧浏览器的简单修复(但确实使用表格,并且需要设置高度):

                      <div style="width:100%;height:40px;position:absolute;top:50%;margin-top:-20px;">
                        <table style="width:100%"><tr><td align="center">
                          In the middle
                        </td></tr></table>
                      </div>
                      

                      【讨论】:

                        【解决方案18】:
                        <style type="text/css">
                        .container_box{
                            text-align:center
                        }
                        .content{
                            padding:10px;
                            background:#ff0000;
                            color:#ffffff;
                        

                        }

                        使用 span 代替内部 div

                        <div class="container_box">
                           <span class="content">Hello</span>
                        </div>
                        

                        【讨论】:

                          【解决方案19】:

                          我知道这个问题很老,但我正在努力解决。与 bobince 的答案非常相似,但有工作代码示例。

                          使每个产品成为一个内联块。将容器的内容居中。完成。

                          http://jsfiddle.net/rgbk/6Z2Re/

                          <style>
                          .products{
                              text-align:center;
                          }
                          
                          .product{
                              display:inline-block;
                              text-align:left;
                          
                              background-image: url('http://www.color.co.uk/wp-content/uploads/2013/11/New_Product.jpg');
                              background-size:25px;
                              padding-left:25px;
                              background-position:0 50%;
                              background-repeat:no-repeat;
                          }
                          
                          .price {
                              margin:        6px 2px;
                              width:         137px;
                              color:         #666;
                              font-size:     14pt;
                              font-style:    normal;
                              border:        1px solid #CCC;
                              background-color:   #EFEFEF;
                          }
                          </style>
                          
                          
                          <div class="products">
                              <div class="product">
                                  <div class="price">R$ 0,01</div>
                              </div>
                              <div class="product">
                                  <div class="price">R$ 0,01</div>
                              </div>
                              <div class="product">
                                  <div class="price">R$ 0,01</div>
                              </div>
                              <div class="product">
                                  <div class="price">R$ 0,01</div>
                              </div>
                              <div class="product">
                                  <div class="price">R$ 0,01</div>
                              </div>
                              <div class="product">
                                  <div class="price">R$ 0,01</div>
                              </div>
                          </div>
                          

                          另见:Center inline-blocks with dynamic width in CSS

                          【讨论】:

                          • 这个答案不是已经提供了相同的解决方案吗? stackoverflow.com/a/284064/547733
                          • 你是对的,疯子!虽然它没有那么健壮。此外,我意识到将 text-align 设置为左​​或右意味着这将永远不会在包含从左到右阅读顺序切换到从右到左的翻译的网站上工作。 text-align 用于对齐文本,而不是元素。理想情况下,在不久的将来,我们将依赖 display:flex 来处理这类事情。
                          【解决方案20】:

                          这是在不知道元素内部宽度的 div 中居中任何内容的一种方法。

                          #product_15{
                              position: relative;
                              margin: 0 auto;
                              display: table;
                          }
                          .price, img{
                              position: absolute;
                              top: 50%;
                              left: 50%;
                              transform: translate(-50%, -50%);
                          }
                          

                          【讨论】:

                            【解决方案21】:

                            我的解决方案是:

                            .parent {
                                display: flex;
                                flex-wrap: wrap;
                            }
                            
                            .product {
                                width: 240px;
                                margin-left: auto;
                                height: 127px;
                                margin-right: auto;
                            }
                            

                            【讨论】:

                              【解决方案22】:

                              将此 CSS 添加到您的 product_container 类中

                                  margin: 0px auto;
                                  padding: 0px;
                                  border:0;
                                  width: 700px;
                              

                              【讨论】:

                              • 问题具体说“没有宽度”
                              猜你喜欢
                              • 2014-04-22
                              • 2023-04-01
                              • 2014-06-26
                              • 2014-11-18
                              • 1970-01-01
                              • 1970-01-01
                              • 2012-03-24
                              • 1970-01-01
                              • 2011-01-21
                              相关资源
                              最近更新 更多