[SalesForce] Line breaks in Lightning component HTML source code put space around the element

While tinkering with Lightning base components, I realized that a linebreak – which may seem to have no effect at all – can actually have a visual impact. I don't have a strong HTML background so I'm asking here.

I was trying to a invoke lightning:tab component, with icon. This is the code and resulting visual:

<lightning:tab>
        <aura:set attribute="label">
            <lightning:icon iconName="utility:open" size="x-small" />Open
        </aura:set>
        Content1
    </lightning:tab>

Tab icon and label has no space inbetween

Then I add a linebreak after lightning:icon as below:

<lightning:tab>
        <aura:set attribute="label">
            <lightning:icon iconName="utility:open" size="x-small" />
            Open
        </aura:set>
        Content1
    </lightning:tab>

And now there's a space between icon and label, which now looks fine:

Tab icon and label has space inbetween

If I hadn't realized that, I was going to add slds-margin class attribute to each lightning:icon component, which is extra code.

Is this an expected behavior? If so, please redirect me to an online source where I can learn such HTML "secret spots".

Best Answer

All Lightning Design System components presume that you do not include any extra space before or after text/elements. HTML collapses multiple white space into a single white space if any are present. The following are rendered the same:


<a> Link Text </a>

<a>         Link        Text      </a>

<a>
  Link            Text
</a>

This is a problem with HTML in general, not specific to Lightning Components. When in doubt, do not introduce new white space, but instead use the appropriate padding CSS elements provided to you by SLDS.

Specific to Lightning Tabs, it is recommended that there be a space between the text, as demonstrated in the documentation:

 <aura:component>
    <lightning:tabset>
        <lightning:tab>
            <aura:set attribute="label">
                Item One
                <lightning:icon iconName="utility:connected_apps" />
            </aura:set>
        </lightning:tab>
    </lightning:tabset>
</aura:component>
Related Topic