我有一个问题,当我试图中心的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>


当前回答

我的解决方案是:

.parent {
    display: flex;
    flex-wrap: wrap;
}

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

其他回答

默认情况下,div元素显示为块元素,因此它们有100%的宽度,使得居中没有意义。正如Arief所建议的,你必须指定宽度,然后你可以在指定边距时使用auto,以便将div居中。

或者,您也可以强制display: inline,但这样您就会有一些行为非常像span而不是div的东西,所以这没有多大意义。

显示:表;并将margin设置为auto

重要代码:

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

不管你现在有多少个元素,它都会自动在中心对齐

代码片段中的示例:

.relatedProducts { 显示:表; margin-left:汽车; margin-right:汽车; } 一个{ 文字修饰:没有; } <div class="row relatedProducts"> <div class="homeContentTitle" style="margin: 0px auto - 35px;类似产品</div> . width: 250px"> <a href="#">test1 </a> <a href="#">test2 </a> <a href="#">test3 </a> < / div >

我的解决方案是:

.parent {
    display: flex;
    flex-wrap: wrap;
}

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

在旧浏览器中工作的简单修复(但使用表格,并需要设置高度):

<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>
<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%(左:50%),然后将其在相反的方向上转换50% (transform:translateX(-50%))来居中。这无需定义目标元素的宽度(或使用width:auto)。父元素的位置可以是静态的、绝对的、相对的或固定的。