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:
<!-- 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>