July 7, 2015

Relational styling with CSS



As everyone knows CSS is used for styling webpages. There are actually a lot of ways to select and style a particular element of html element. You can also style multiple elements at a time. In this post I will show all the possible ways to style a particular elements.

html 

<section>
       <div>
              <p id="paragraph1" class="para">Hello I am first paragraph.</p>
       <div>
      
      <div>
              <p id="paragraph2" class="para">Hello I am second paragraph.</p>
       <div>
</section>

This is the html part to which we are going to apply the styles in a couple of seconds. I will show you styling the two paragraphs in multiple ways. Let's achieve it.

Using Direct elemental selections

p {
   font-size: 20px;
   color: blue;
}

We can directly select the particular element and style it as I show you in the above code snippet.

Using Classes

.para {
     font-size: 20px;
     color: blue;
}

In the above code snippet we have used it's class to achieve same result over selecting the p element directly.

Using ID's

#paragraph1 {
      font-size: 20px;
      color: blue;
}
#paragraph2 {
     font-size: 20px;
     color: blue;
}

Generally, if  you want to apply same styles for different elements Designers use classes rather than Id's. But, any how I just show one of the possible ways.

Using Relational Styling

We can also style the elements using their tree structures. In simple way parent child relations. Here if you observe the html structure once each div is the child of section and paragraph is the child of div and grand child of section. Using this relation we will style the paragraphs now.

section > div > p {
       font-size: 20px;
       color: blue;
}

We can also style this in the other way.

section p {
    font-size: 20px;
    color: blue;
}

So, these the different ways you can style the elements. Depending up on your comfortability you can choose any way you want or you can use all these ways for different elements.

No comments: