I have the following HTML to render a date input box with an icon:
@if (Model.ShowThis){
<input id="box1" type="hidden" value="@Model.SelectedDate.ToString("yyyy-MM-dd")" size="10" />
<span id="icon1" class="picture"></span>
}
You'll notice that the icon is shifted to the right. If I modify the code to be:
@if (Model.ShowThis){
<input id="box1" type="hidden" value="@Model.SelectedDate.ToString("yyyy-MM-dd")" size="10" /><!--
--><span id="icon1" class="picture"></span>
}
you will notice that there is no longer a shift due to the removal of any potential white space. Without these comments, I can go into the debugger and see extra spacing between the elements, which once removed, fixes the problem as well.
Why are standard new lines within a .cshtml file (inside a Razor block) causing there to be non-breaking spaces between these HTML elements? I have never seen this behavior before in other files in the same type of scenario.
You're seeing white-space in your HTML document rendered as these are both inline-block
elements, I'm guessing.
Think of them not as elements on a page, then, but words in a sentence. The browser does it this way. So, if I put:
<div>
Here
is
a
sentence.
</div>
in HTML, I'd expect to see:
Here is a sentence.
in my document. This is because HTML interprets aggregate strings of white-space (including line breaks and register returns) as cumulatively one space when rendering. It expects a tag to forcibly break a line, if that's the desire. Given white-space: normal
(the CSS default), if there's not enough space for the text on the line, then it will wrap. This allows for well-formatted and readable HTML (which is an aside, but it's important to understand why it works this way).
It's the same story with inline
or inline-block
elements. They're handled much like text in layout, and thus respect surrounding white-space. That's good, because that's intended behavior for inline elements. You just need to make some special considerations when you lay out your document using those display properties.
Either leave your HTML comment in the code, or use this pattern in CSS:
.container {
font-size: 0;
}
.container > * {
font-size: 1rem;
}
where .container
is whatever wrapper you have around the offending elements.
It's not a Razor thing; even static HTML would have the same problem. Whitespace will unfortunately affect layout, whether it's line breaks or spaces.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With