0

I'm facing a little problem, I have a css class which is called "negative margin" which I just want to apply once in the first div in a series of divs as it's part of my design. The code is as follows:

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

The class negative-margin is applied to all the divs making them stack on top of each other and it's not what I wan't but I need this negative margin to be applied in the first div as I said for design purposes but I really don't know how this could be achieved. Any ideas would be greatly appreciated.

2
  • 2
    You could use an index and a conditional statement to track the first div. Commented Jul 7, 2015 at 17:17
  • 1
    Can you use css only on the parent tag? If yes, you can use css target :not(:first-child) Commented Jul 7, 2015 at 17:18

2 Answers 2

4

You need a variable to track the first element because there is no other way to know the index in foreach loop. You can do:

<?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; ?>
Sign up to request clarification or add additional context in comments.

Comments

4

Use the first-child selector to define a CSS style that only applies to the first div.

div.grid:first-child { 
    margin-left: -10px;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.