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?
2
Answers
If you are within a bootstrap
row
and just usingcol-*
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 providedJust curious, is there a good reason why you’re wanting to specify the column widths if generating the column divs in a loop? By using the
col-4
class you’re limited to only looping over 3 items every time (unless you modify the default$grid-columns
setting to be larger than 12, of course), and as you’re obstensibly expecting these divs in this example to be equal-width, you may as well just usecol
instead and let the divs auto-format.Doing so should keep all elements on the same row:
I wouldn’t think that whitespace/newline should make any difference… but it does sound like it’s behaving as if the aggregated column widths exceed the max grid columns, even though that shouldn’t be the case (again, assuming that the default
$grid-columns
Sass variable value hasn’t been reduced).Alternatively (or additionally), you can try using the inline flex display class for the container, like so: