1.3 Apply styling to lightning component

In this post, we will be learning how to use html and css in lightning component. Salesforce has actually made the process very straight-forward. Let’s take a look!

The code

Below is the sample code. First, let’s adjust our previous¬†HelloWorldCmp code into below:

<aura:component>
    <div class="white">
        Hello World!
    </div>

    <h2>Check out the style in this list.</h2>
    <ul>
        <li class="red">I'm red.</li>
        <li class="blue">I'm blue.</li>
        <li class="green">I'm green.</li>
    </ul>
</aura:component>

Now let’s add a style file for this component. If you are using Developer console, you can find a STYLE button at your right hand side. Click it.

Otherwise, if you are using HaoIDE as I am doing, you can write click you component folder and click HaoIDE > lightning style. As shown:

If you are using other IDEs, you need to figure it out by yourself. But most of them are pretty similar and easy.

Now let’s pop in the code:


.THIS {
    background-color: grey;
}

.THIS.white {
    background-color: white;
}

.THIS .red {
    background-color: red;
}

.THIS .blue {
    background-color: blue;
}

.THIS .green {
    background-color: green;
}

Doesn’t look very different than normal html and css files, right?

Let me explain a little bit more about those.

A little bit explanation for using Html in lightning component

Html tags are treated as first-class citizens in lightning component. The majority of Html5 tags are supported by lightning component.

However, Salesforce do consider some of the Html tags are unsafe or unnecessary, or both. So the framework doesn’t support these tags:

  • applet
  • base
  • basefont
  • embed
  • font
  • frame
  • frameset
  • isindex
  • noframes
  • noscript
  • object
  • param

A little bit explanation about using Css in lightning component

The css code need to be put into a separate style file. You can’t inject them directly into the component’s code.

In the style file, everything starts with .THIS, which means the top level of the component.

So the top level components, including h2 and ul, matches .THIS class with a grey background.

Please note that .white class is in the top layer so there is no space between .THIS and .white. Red, blue and green classes are one layer deeper, so they need a space between .THIS and .[className].

Next Post

1.4 Use attributes to carry information

Subscribe to Sfdcinpractice

Subscribe to get the latest blogs and tutorials of sfdcinpractice. No spam, no trash, only the awesome posts from sfdcinpractice. 

Leave a Reply

Your email address will not be published / Required fields are marked *