我面临一个小问题,我有一个css类,它被称为"负边距",我只是想在第一个div系列div应用一次,因为它是我设计的一部分。代码如下:
<?php foreach($records as $rec){ ?>
<div class="grid grid-lightgrey grid-pad negative-margin">
<div class="col-1-1">
<div class="module module-grey">
<em>Project title: <?php echo $rec->project_title; ?></em><br>
<em>Category: </em><?php echo $rec->project_category; ?><br>
<em>Description: </em><?php echo $rec->project_description; ?>
<br>
<em>This project was started in: <?php echo $rec->project_year; ?></em><br>
<em>This project ID is: </em>
<?php echo $rec->project_id; ?>
</div>
</div>
</div>
<?php } ?>
类negative-margin应用于所有div,使它们堆叠在一起,这不是我想要的,但我需要这个负边距应用于第一个div,正如我所说的设计目的,但我真的不知道这是如何实现的。
使用第一个子选择器定义只应用于第一个div的CSS样式。
div.grid:first-child {
margin-left: -10px;
}
您需要一个变量来跟踪第一个元素,因为没有其他方法可以知道foreach循环中的索引。你可以这样做:
<?php $i = 0; foreach($records as $rec): ?>
<div class="grid grid-lightgrey grid-pad <?php echo ($i == 0) ? 'negative-margin' : ''; ?>">
<div class="col-1-1">
<div class="module module-grey">
<em>Project title: <?php echo $rec->project_title; ?></em><br>
<em>Category: </em><?php echo $rec->project_category; ?><br>
<em>Description: </em><?php echo $rec->project_description; ?>
<br>
<em>This project was started in: <?php echo $rec->project_year; ?></em><br>
<em>This project ID is: </em>
<?php echo $rec->project_id; ?>
</div>
</div>
</div>
<?php $i++; endforeach; ?>