Empty field takes up space in the layout

So I have a bunch of fields that I only wanna display if there is actually content inside. The code looks like this:

<?php foreach($page->content()->fields() as $field): ?>
            <div class="project__cast__fields">
                <?php if(
                    $field->isNotEmpty() 
                    && $field->key() != "title" 
                    && $field->key() != "uuid"
                    && $field->key() != "tags" 
                    && $field->key() != "summary"
                    && $field->key() != "color"): 
                ?>
                    <div class="one">
                        <p><?= ucfirst($field->key()) ?></p>
                    </div>
                    <div class="two">
                        <p><?= $field->html()->kirbytext() ?></p>
                    </div>
               <?php endif ?>
            </div>
        <?php endforeach ?>

This works, but if I give the class .project__cast__fields some margin at the top or bottom those empty elements seem to add margin as well although they’re not visible otherwise…is there a way to get rid of that?

You are adding an empty div because your if statement should come before that div.

Damn, what a dumb thing to miss…thanks so much!