Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Eliminate whitespace between divs generated from loop

I have a Razor page that I’m attempting to show <div> elements in rows using Bootstrap. Each <div> is generated programmatically like this:

@foreach (var item in Model)
{
    <div class="col-4">
        <!-- content -->
    </div>
}

My problem is that there’s whitespace or a return character or something between each <div> and that causes the last <div> to get pushed to the next line.

So with class="col-4", I should be able to squeeze 3 elements onto one row. But the third one gets pushed to the next row. Typically, when I hardcode this sort of thing, I remove all whitespace between each <div> and it fixes the issue:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<!-- THIS WORKS -->
<div class="col-4">
    <!-- content -->
</div><div class="col-4">
    <!-- content -->
</div><div class="col-4">
    <!-- content -->
</div>

<!-- THIS DOESN'T WORK -->
<div class="col-4">
    <!-- content -->
</div>
<div class="col-4">
    <!-- content -->
</div>
<div class="col-4">
    <!-- content -->
</div>

My question is how do I achieve this when I’m rendering each div programmatically?

>Solution :

If you are within a bootstrap row and just using col-* elements then whitespace should not matter at all. Your code sample has some missing quotes which could be screwing things up, but I can’t tell if that’s a typo in your question or the actual code output.

When the quotes are fixed and put into a row I don’t see any issues at all or even any differences between the two code samples you provided

div[class^="col-"]{
  background: #CCC;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">

<div class="row">
  <!-- THIS WORKS -->
  <div class="col-4">
      1
  </div><div class="col-4">
      2
  </div><div class="col-4">
      3
  </div>
</div>

<br/><br/>

<div class="row">
  <!-- THIS DOESN'T WORK -->
  <div class="col-4">
      1
  </div>
  <div class="col-4">
      2
  </div>
  <div class="col-4">
      3
  </div>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading