November 28, 2019

CSS for Noobs

I have heard a lot that developers are scared of the CSS a lot. I respect that not every person's learning curve and understanding are the same. So here I will talk about the CSS from 2 perspective - important concepts and CSS topics:

* assuming you know how to add CSS to your HTML pages.

How you can add CSS to HTML (DOM)

The first and foremost important thing about CSS is to learn about how to target the HTML elements or how to tie the CSS (style) we are going to write with the HTML. We have different ways we can tie the relationship between HTML and CSS:

Code Example:

1.  dom elements

One can write CSS directly to the HTML DOM elements. Such as if we want to write CSS to the p tag then we will write:

Syntax: p { ... }

2. class

The issue with the writing CSS to HTML elements is it will be applied to all the global elements. If one wants to apply CSS only to selected elements then we can use CSS class.

Syntax: .className { .. }

The benefit of CSS class is you can use them multiple times on the HTML page. I can use .className many times in my HTML page.

3. id

id is the one way of having the styling to the HTML page. Unlike classes, IDs are unique you can have only one ID par page hence we can use IDs to have unique styling. Most developers use IDs to use them in JavaScript but there are no such restrictions of not using IDs for styling.

Best to write classes and use classes more in CSS. Reason: for the purpose of reusability.

Syntax: #container {....}

4. selectors

The examples we have seen so far our the direct CSS applying to the HTML elements. Eg; add CSS to the div after p tags. How you will do this? For this we could make the CSS class or id and apply but what if the div(s) are dynamically getting generated and you can't add to DOM.

CSS provides 'selectors' for such a situation.  There are many different types of selectors. Important ones are:

(a) *   (To apply the styling to all the elements)

syntax* {...}

(b) + (It selects the adjacent elements)

syntaxp + p {...}

(c) space: (to select the children)

Syntax: div span {...}

(d) > : (Direct children)

Syntax: div > li {...}

(e) ~ : (Subsequent-sibling Combinator)

Syntaxli ~  span {...}

The problem with the  + selector is that it will only apply to the subsequent element. To apply the styling to all the elements we use ~

For more check CSS tricks article

5. pseudo-elements

In CSS pseudo-elements get used to styling a part of the elements. Eg: if we want to style the First-letter, first-word, etc. From CSS3 onwards we use:: (double colon) rather than : (single colon). To differentiate between the pseudo-elements and classes.

Eg: :first-letter {...}  , ::first-line

6. pseudo-classes   

:hover, :visited,  : focus , ::after, ::before , :not

Happy Learning!!

No comments: