如何对齐动态生成的div或段落

时间:2017-03-11 10:49:40

标签: php jquery html css

我想显示一个产品页面,其中每个项目彼此对齐。这些产品是使用PHP代码动态生成的。问题是,当一个产品的名称比另一个产品的名称更长时,它们不会水平对齐。

要进一步了解我的问题,请点击此处截图: Product misalignment screenshot

您可以看到产品价格彼此不一致,因为它们受产品名称长度的影响。

这是我的PHP和HTML代码:

<!--PHP CODE FOR EXTRACTING DATA FROM TABLE-->
<div class="span_container">
                        <div class="col-md-4 bottom-cd simpleCart_shelfItem" style="display: inline-block;">
                            <div class="product-at ">
                                <a href="single.php"><img class="img-responsive" style="width:300px; height:auto;" src="/EDGE/storeadmin/product_images/<?php echo $row['i_image']; ?>" alt="">
                                <div class="pro-grid">
                                            <span class="buy-in">View Details</span>
                                </div>
                            </a>
                            </div>
                            <p class="tun"><?php echo $row['i_name'];?></p>
                            <a href="checkout.php" class="item_add"><p class="number item_price"><i> </i>₱<?php echo $row['i_price']; ?></p></a>
                        </div>
                    </div>

这是我的段落(tun)的CSS代码:

    p.tun {
    font-size:1em;
    color: #949494;
    text-align: center;
    line-height: 1.3em;
    padding: 1em 0;
}

2 个答案:

答案 0 :(得分:1)

这很简单。为包含position:relative;类设置.simpleCart,为height:300px设置高度 - 将300替换为您需要的盒子高度,以便每个包含的框具有相同的高度。

然后使用position:absolute;根据我们已知的高度将元素定位在.simpleCart内。

我们知道并可以推断:

  • 图片的高度:因此我们使用position:absolute;top:5%;作为示例: - 根据您的需要更改5%。
  • 产品价格的高度,无论.simpleCart盒子有多高,它们都会在底部。所以我们使用position:absolute;bottom:5% - 再次根据您的需要更改5%。现在每个产品价格都处于同一水平。只要每个.simpleCart框具有相同的高度。
  • 最后,我们将段落文本与.tun类放在position:absolute;top:150px;之间 - 根据您的需要更改150,以便它适合图像和产品定价。

答案 1 :(得分:0)

您可以使用以下js函数将模块高度与最高版本匹配。

&#13;
&#13;
equalheight = function(container){

var currentTallest = 0,
     currentRowStart = 0,
     rowDivs = new Array(),
     $el,
     topPosition = 0;
 $(container).each(function() {

   $el = $(this);
   $($el).height('auto')
   topPostion = $el.position().top;

   if (currentRowStart != topPostion) {
     for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {
       rowDivs[currentDiv].height(currentTallest);
     }
     rowDivs.length = 0; // empty the array
     currentRowStart = topPostion;
     currentTallest = $el.height();
     rowDivs.push($el);
   } else {
     rowDivs.push($el);
     currentTallest = (currentTallest < $el.height()) ? ($el.height()) : (currentTallest);
  }
   for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {
     rowDivs[currentDiv].height(currentTallest);
   }
 });
}

$(window).load(function() {
  equalheight('.equalise-height');
});
&#13;
&#13;
&#13;