Search code examples
htmlbuttontags

Closing tag with comment produce "strange" behaviour


Please someone can explain me why if i put the closing tag in a new line and i put a comment between one button and another the white space between the buttons isn’t and the button is positioned side by side the other? Otherwise between a button and another a little white space is rendered, like the second and the third one. Can a comment change how an element is rendered by the browser?

Like this:

<div class="segmented-control__row">
      <button
        class="segmented-control__button segmented-control__button--active js-segmented-control__button"
        data-value="1"
      >
        Sort by price</button
      ><!--
            --><button
        class="segmented-control__button js-segmented-control__button"
        data-value="2"
      >
        Sort by name
      </button>
      <button
        class="segmented-control__button js-segmented-control__button"
        data-value="3"
      >
        Sort by relevance
      </button>
    </div>

the first one is with comment the second without. This is the result. enter image description here

Thank you


Solution

  • In HTML, whitespace isn't entirely ignored. A lot of whitespace (newlines, tabs, spaces) will be reduced to a single space, but that space can sometimes cause problems with your layout.

    One option is to remove the whitespace entirely, and have the HTML on a single line.

    Another option, the one you came across, is to use a comment. By placing the whitespace inside a comment, it won't be rendered and mess with your layout.

    Info on whitespace in HTML: https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Whitespace