Why do these HTML elements in .NET Razor have extra spacing caused by newlines?

I have the following HTML to display a date input field 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> } 

Icon shifted to the right

You will notice that the icon is shifted to the right. If I modify the code:

 @if (Model.ShowThis){ <input id="box1" type="hidden" value="@Model.SelectedDate.ToString("yyyy-MM-dd")" size="10" /><!-- --><span id="icon1" class="picture"></span> } 

Icon in correct place

You will notice that there is no longer a shift due to the removal of any potential gap. Without these comments, I can enter the debugger and see the additional distance between the elements that are fixed after removal and the problem.

Why do the standard lines in the .cshtml file (inside the Razor block) cause inextricable spaces between these HTML elements? I have never seen this behavior in other files in the same type of script.

+6
source share
2 answers

You see white space in your HTML document, as shown in both inline-block elements, I assume.

Think of them not as elements on a page, but as words in a sentence. The browser does it like this. So, if I put:

 <div> Here is a sentence. </div> 

in HTML, I would expect to see:

Here is a suggestion.

in my document. This is because HTML interprets cumulative white space strings (including line breaks and returned registers) as cumulatively one space when rendering. He expects the tag to forcibly break the line if it is a desire. Given white-space: normal (CSS by default), if there is not enough space for the text in the line, it will complete. This allows for well-formatted and readable HTML (which is aloof, but it’s important to understand why it works this way).

This is the same story with inline or inline-block elements. They are processed in the same way as the text in the layout, and thus respect the environment. This is good because this is the intended behavior for inline elements. You just need to make some special considerations when you lay out your document using these display properties.

Either leave an HTML comment in the code, or use this template in CSS:

 .container { font-size: 0; } .container > * { font-size: 1rem; } 

where .container is some kind of shell that you have around offensive elements.

+5
source

This is not a razor thing; even static HTML would have the same problem. Spaces, unfortunately, will affect the layout, whether line breaks or spaces.

+1
source

Source: https://habr.com/ru/post/986779/


All Articles