To Space or not to Space? - El Toro - Find articles about Visualforce, Apex, Force.com and Salesforce in general

Print Preview

To Space or not to Space?

That’s the question!

There is a known English writer (you know who) that asked this same question, but I think he was actually talking about CSS in the Lightning Components... Let me first show you the problem.

Let's first take a look at this code:

<aura:application >
	<div class="redFont">
        Red Letters
    	<div class="blueFont">
        	Blue Letters
        </div>
    </div>
</aura:application>


.THIS.redFont {
    color: red;
}

.THIS .blueFont {
    color: blue;
}

This code is quite simple and it does work. But did you notice there is a space before .blueFont, and not before .redFont? And if you add/remove the space the code will not work!!! So the question is "To Space or not to Space?". The reason has to do with CSS, but that is beyond this simple post. What I do want to do here, is to help you remember easily if you do or do not put a space. Let's take a close look at the code and see the parts that make this simple DOM.

Although the reason has to do with the DOM and CSS, let's take a simpler look at this... If you indent the code properly (remember it does not have to do with the indentation, but it helps seeing it this way) you can clearly see the need for space. Let's take a look...

After indenting properly, you can see an imaginary yellow line indicating which elements are at the root of the component and some elements that are spaced from that imaginary line. This is what I want you to remember....

If there is a space, you put a space!

Basically, if you are setting the class for an element at the root of the component, then there is no space between THIS and the class name, but if you are setting something that is not at the root then you do need the space.

The next obvious question is what do you do if the class needs to be defined for an element at the root and not root? Great question, I am glad you asked. Here is the answer:

<aura:application>
    <div class="redFont">
        Red Title
    </div>
    <p>            
        Hello 
        <span class="redFont">
            World
        </span>
    </p>
</aura:application>

.THIS.redFont, .THIS .redFont {
    color: red;
}

Another simple approach is to put a big <Div /> surrounding all the markup, so that we do not care about things at the root ;-)

comments powered by Disqus

© El Toro . IT @ 2013
Andrés Pérez