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

其他回答

显示:表;并将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 >

将这个CSS添加到product_container类中

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

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

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

我找到了一个更优雅的解决方案,结合“内联块”来避免使用float和俗气的clear:两者。它仍然需要嵌套的divs,这不是很语义,但它只是工作…

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

div.inner{
    position:relative;
    left:-50%;
}

希望能有所帮助!

我的解决方案是:

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

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