2012-12-19 25 views
3

這裏是我的代碼:如何在使用循環打印時在DIV上應用邊距?

<?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/

輸出請幫我,我怎麼能申請的10px的邊距兩側(左&右),只在使用php循環打印時,每行的中心div。

+0

你在一排有多少個盒子? –

+0

如果你需要使用nth-child的幫助,你可以訪問http://codepen.io/RadLikeWhoa/full/cAJEo看看你想要什麼 – ashley

+0

@PankitKapadia,單行3盒 – Moeen

回答

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; 
?> 
+1

謝謝,解決了我的問題。 – Moeen

+0

@Meen - 快樂! :) –

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解決方案。如果你忘記了左邊距,只需要使用正確的邊距,就可以將它從最後一個孩子中移除。更少的CSS線更好的性能。

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