如何在循环打印时给DIV应用边距?

3

这是我的代码:

<?php 
     $qr = mysql_query("SELECT * FROM products");
     while($res = mysql_fetch_array($qr)):
?>

<div class="box">
    <p><?php echo $res[1]; ?></p>
    <img src="<?php echo $res[3]; ?>" width="100" /><br />
    <a href="<?php echo $res[4]; ?>">View Data Sheet</a>            
</div>

<?php 
    endwhile; 
?>

我希望获取的记录输出结果像这样:http://jsfiddle.net/CqYhE/3/ 请帮我解决如何在使用php循环打印时,仅对每行中心div应用10px左右边距的问题。

你一排有多少个盒子? - Pankit Kapadia
如果你需要关于使用nth-child的帮助,你可以访问http://codepen.io/RadLikeWhoa/full/cAJEo 来查看你想要的。 - ashley
@PankitKapadia,一排三个盒子。 - Moeen
3个回答

2

这是您的解决方案:

该方案适用于N个部门。

<?php 
    $qr = mysql_query("SELECT * FROM products");

    $count = 1;
    $margin='';

    while($res = mysql_fetch_array($qr)):
        $count == 2 ? $margin='style="margin:0px 10px;"' : $margin = '';
        $count == 3 ? $count = 1 : $count++;
?>    

    <div class="box" <?php echo $margin; ?>>
        <p><?php echo $res[1]; ?></p>
        <img src="<?php echo $res[3]; ?>" width="100" /><br />
        <a href="<?php echo $res[4]; ?>">View Data Sheet</a>            
    </div>

<?php 
    endwhile; 
?>

0

使用 CSS 的 :first-child:last-child 选择器

#container .box{
    float: left;
    width:245px;
    height:200px;
    background-color:#0CC;
    margin-bottom:10px;
    margin-left:10px;
    margin-right:10px;
}
#container .box:first-child,
#container .box:last-child { margin-left:0px; margin-right:0px;}

如果您有多行数据,您需要更改您的HTML以使其更容易:请参见此DEMO


0

这可以通过CSS解决方案最好地实现。如果您忘记左边距,只需应用右边距,然后可以从last-child中删除它。更少的CSS行数,更好的性能。

.box{
    float: left;
    width:245px;
    height:200px;
    background-color:#0CC;
    margin: 0 20px 10px 0;
}
.box:last-child {
    margin-right: 0;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接