CSS: Nested Selector vs Modular Selector

Hello Everyone, today I am going to share on two different categories of selectors i.e. Nested Selector and Modular Selector. Let’s quickly jump to check 2 different style aspect without waiting for a moment.

Basically, there are 2 different categories of presenting the style –
1. Nested Selector (shortcut selector)
2. Modular Selector (flexible selector)

Let’s quickly go through one example to make it more clearer. Lets say we have to design the navigation section like below :

nested selector - 1

To design the navigation pad, the code will look like this :

<html>
<head>
    <title>Example of Nested Selector</title>

    <style type="text/css">
        .sidebar {
            box-sizing: border-box;
            float: right;

            .title {
                margin-bottom: 15px;
                margin-top: 20px;
                position: relative;
            }
        }

        .nav {
            list-style: outside none none;
            margin-bottom: 0;
            padding-left: 0;

            > li {
                display: block;
                position: relative;

                > a {
                    display: block;
                    padding: 10px 15px;
                    position: relative;
                }

                &.active {
                    > a {
                        background-color: #fafafa;
                        border: 1px solid #f3f3f3;
                        color: #e84c3d;

                        &:hover {
                            background-color: #fafafa;
                            border: 1px solid #f3f3f3;
                            color: #e84c3d;
                        }
                    }
                }
            }
        }
    </style>
</head>

<body>
<aside>
    <div class="sidebar">
        <h3 class="title">Components</h3>
        <div class="separator"></div>
        <nav>
            <ul class="nav nav-pills nav-stacked">
                <li class="active">
                    <a href="">Tabs & Pills</a>
                </li>
                <li><a href="">Accordions</a></li>
                .........
                <li><a href="">Image Boxes</a></li>
            </ul>
        </nav>
    </div>
</aside>
</body>
</html>

The above code is a simple example on how nested css can be written. But guys, did you find the problem with the above code. Can we use only .sidebar style (title with different css) in any other place in future?

No .. right!! As the styles are nested, we can not use the component separately as we want.

So, if we want to reuse each and every style what we have written so far, we have to use Modular way to design the style.

Lets check the same example in a Modular way !!

<html>
<head>
    <title>Example of Modular Selector</title>

    <style type="text/css">
        .sidebar {
            box-sizing: border-box;
            float: right;
        }

        .sidebar .title {
            margin-bottom: 15px;
            margin-top: 20px;
            position: relative;
        }

        .nav {
            list-style: outside none none;
            margin-bottom: 0;
            padding-left: 0;
        }

        .nav > li {
            display: block;
            position: relative;
        }

        .nav > li > a {
            display: block;
            padding: 10px 15px;
            position: relative;
        }

        .nav > li.active > a, .nav > li.active > a:hover {
            background-color: #fafafa;
            border: 1px solid #f3f3f3;
            color: #e84c3d;
        }
    </style>
</head>

<body>
<aside>
    <div class="sidebar">
        <h3 class="title">Components</h3>
        <div class="separator"></div>
        <nav>
            <ul class="nav nav-pills nav-stacked">
                <li class="active">
                    <a href="">Tabs & Pills</a>
                </li>
                <li><a href="">Accordions</a></li>
                .........
                <li><a href="">Image Boxes</a></li>
            </ul>
        </nav>
    </div>
</aside>
</body>
</html>

So, now can we use only .sidebar class for any other styles? A BIG YES right !!! 🙂

Nested selectors are more complex and those are less readable. But, it has its own advantages of targeting DOM elements. Maintainability is easy as, we just need to do fewer changes when the class name need to be changed later. The code will look concise and the selector looks pretty.

But, now-a-days CSS is getting more modular. It is modulated into different defaults, components, and settings and developer/designer should take 100% advantage of doing so. With modular CSS, coding is much easier like writing simple HTML. Styles will be consistent and easier to reuse the modules. Once the base been created, it would be easier to do modification in future. Then the subsequent development time will be very less. It simplify the code as clashes will not happen with this type of styling.

Much theories !! 😀 Ahh .. I know :).. Let’s stop then. Now you decide which one is better and why. Do you really find it useful? 🙂 If yes, then please like and add some comments, if you want.

Thanks 🙂 and I will be happy to hear from you 🙂 :).

Advertisements

CSS: Creating nested numbered list using CSS-Counters

Hello everyone, today I am going to share one basic thing, which you all may know about it. I am going to explain how can we create numbered list using CSS. So, let’s go through it quickly without wasting much of our time :).

HTML provides us few ways of creating lists. A list can be created using either of the following 3 ways i.e.

  • Unordered List
  • Ordered List
  • Description List

Let’s have a look at the results created by the above 3 lists –

counters-1counters-2counters-3

As the post title suggests, we will have our focus on Numbered List, we’ll consider only the case of Ordered List which alternatively known as Numbered List.

Let’s notice the default behavior of a numbered list. The sub-numbered list has started numbering from 1 to n, once again. Now, what if I need those to be numbered like 1.1, 1.2, 1.3… so on?

This can be done in various ways using Javascript OR CSS.. WAIT ! umm … CSS?
With alone CSS can we achieve this?

Yes, we can :). I know, the primary use of CSS is to describe the presentation semantics of an HTML document but, we can also use CSS for content generation. With the use of Content property along with pseudo-elements like :before, :after etc. we can inject a piece of content into an HTML element. But here our HERO is “CSS-Counters”. Let’s quickly go through this. There are 3 properties for CSS-counters –

  1. counter-reset: counter-name /* initializes or resets the counter */
  2. counter-increment: counter-name /* increments counter values */
  3. content: counter (counter-name) /* evaluates to counter value */

Let’s go through an example :

<!DOCTYPE html>
<html>
    <head>
        <style>
            body {
                counter-reset: section;
            }

            h1 {
                counter-reset: subsection;
            }

            h1:before {
                counter-increment: section;
                content: "Section " counter(section) ". ";
            }

            h2:before {
                counter-increment: subsection;
                content: counter(section) "." counter(subsection) " ";
            } 
        </style>
    </head>
    <body>
        <h1>Wordpress</h1>
        <h2><a href="https://pravasini.wordpress.com">https://pravasini.wordpress.com</a></h2>
        <h2><a href="http://suvendugiri.wordpress.com">http://suvendugiri.wordpress.com</a></h2>
        <h2><a href="http://tanmayabiswal.wordpress.com">http://tanmayabiswal.wordpress.com</a></h2>

        <h1>CodeProject</h1>
        <h2><a href="http://www.codeproject.com/Members/prava-mfs">http://www.codeproject.com/Members/prava-mfs</a></h2>
        <h2><a href="http://www.codeproject.com/Members/SuvenduShekharGiri">http://www.codeproject.com/Members/SuvenduShekharGiri</a></h2>
        <h2><a href="http://www.codeproject.com/Members/taditdash">http://www.codeproject.com/Members/taditdash</a></h2>

        <h1>Stack Overflow</h1>
        <h2><a href="http://stackoverflow.com/users/2269132/prava">http://stackoverflow.com/users/2269132/prava</a></h2>
        <h2><a href="http://stackoverflow.com/users/1006297/suvendu-shekhar-giri">http://stackoverflow.com/users/1006297/suvendu-shekhar-giri</a></h2>
    </body>
</html>

The above code will generate :
result

Isn’t it interesting!!! 🙂 Just using CSS, we can generate the contents as like above styling. Do you really find it useful? 🙂 If yes, then please like and add some comments, if you want.

Thanks 🙂 and will be happy to listen from you 🙂 :).

Beginners guide on CSS Selectors

As we all know about CSS (Cascading Style Sheets) is a language used for styling the web pages written in HTML, XML or XHTML. In CSS, selectors play a vital role to declare which part of the web page, the style applies to and it is done by matching the tags or attributes present in that web page. It’s very simple to write the tags or attributes for applying the selector, but need some tricks to precise and reuse it. Today in this post, we will go through the type of selectors, its advantages, introduced in every version of CSS.

CSS1 :-

ID Selector :- Selects one element that has a given id attribute. Below example will apply black border to the element which id equals to ‘idMyTest’.

#idMyTest {
    border: 1px solid black;
}

 

Class Selector :- Selects one or more element that has the given class attribute. The below will apply black background to all the elements where the class defines as ‘class-my-test’ in the html document.

.class-my-test {
    border: 1px solid black;
}

 

Type Selector :- Selects every element that has the given type node. Type node can be ‘span’, ‘p'(paragraph), ‘div’, ‘a'(hyperlink), ‘img’ etc.. The example will add border to all the span present in the web document.

span { 
    border: 1px solid black;
}

 

Descendant Combination Selector :- Selects all the elements with the type. For below example, it will select all elements inside elements. The below will apply the border to the hyperlink present inside or as child of span element.

span a {
    border: 1px solid black;
}

 

Link History Pseudo-Class Selector :- Selects all unvisited link only. The below will make all the link elements color as blue.

:link {
    color: blue;
}

 

User Action Pseudo-Class Selector :- Selects all matched elements which are activated by any user. The below example will make green as background color for the active buttons.

button:active {
    background-color: green;
}

 

CSS2 :-

Universal selector :- Selects every element of any type, that means apply style to all the attribute of the web page. Below will add black border to all the elements present in DOM.

* {
    border: 1px solid black;
}

 

User action pseudo-class selectors :- Apply the styles on hover or on focus of any element. The below code will make red background on hover of the element where the class name mentioned as ‘btn’.

.btn:hover {
    background-color: red;
}

 

Dir pseudo-class selector :- Select elements by its directionality based on the mentioned document language. The values are ‘ltr’ (left to right) and ‘rtl’ (right to left). The below will apply green background to the element where the text start from left to right, and applies red background to the element where the text start from right to left.

:dir(ltr) {
    background-color: green;
}

:dir(rtl) {
    background-color: red;
}

 

Lang pseudo-class selector :- Selects all the elements mentioned in the document language. The language value can be any 2-digit international language (en, fr, nl, de, etc..). The below will apply red color to the text which will be in english language.

:lang(en) {
    color: red;
}

 

Attribute selectors :- Selects matching string in the value attribute. The below example select all elements which have an title attribute and add a black border.

[title] {
    border: 1px solid black;
}

 

Structural pseudo-class selector :- Selects the first-child of the given attribute. The below will select the first child (can be a span or div or p element) of span and apply black border to it.

span :first-child {
    border: 1px solid black;
}

 

Child combination selector :- Select the direct child elements of the mentioned parent/first selector. The below example will add border to the first span present inside the div.

div > span {
    border: 1px solid black;
}

 

Adjacent sibling combination selector :- Select an element immediately preceded by another element. For the below example, border will apply to <p> elements, placed immediately after <div> elements.

div + p {
    border: 1px solid black;
}

 

CSS3 :-

Negation pseudo-class selector :- Selects every element that is not of the given element type. The below example applies border to all the element present inside the div, except <p> element.

div :not(p) { 
    border: 1px solid black; 
}

 

Target pseudo-class selector :- Selects the element being the target of the referring URI. The below will add border to the ‘heading4’ text on click of ‘First’ link.

h4:target {
    border: 1px solid black;
}
<h4 id="one">heading4</h4> 

<p>paragraph</p>
<div id="three">DIV</div>
<a href="#one">First</a>
<a href="#two">Second</a>
<a href="#three">Third</a>

 

Scope pseudo-class selector :- Match the elements that are a reference point for selectors to match against. The below will make lime background color for “Inside scope.”.

<div>
    It match the elements that are a reference point for selectors to match against.
    <section>Outside scope.</section>
    <section>Inside scope.</section>
    <section>Outside scope.</section>
</div>

 

Enabled and Disabled pseudo-class selectors :- Select every enabled/disabled element. The below example will add green border to the enabled input element and gray border to the disabled input element.

:enabled {
    border-color: green;
}
 
:disabled {
    border-color: gray;
}

 

Selected-option pseudo-class selector :- Select every checked input element i.e. will apply the style to the radio or select element. The below will make the option as red color on checked.

:checked {
    color: red;
}

 

Structural pseudo-class selectors :- It select the root element of the document or the web page. The example will make the background color as red for the root element in the hierarchy.

:root {
    background-color: red;
}

 

Attribute selectors :- Selects every element whose attribute value begins with given string. The below will select every <a> element and make the color red, where href attribute value starts with “https”.

a[href^="https"] {
    color: red;
}

 

General sibling combinator selector :- Selects the second element only if it is preceded by the first, and both share a common parent. The below will make red color to ‘Second Span’ text.

p ~ span {
  color: red;
}

<span>First Span</span>
<p>Paragraph</p>
<div>Code Example</div> 
<span>Second Span</span>

 

CSS4 :-

Negation pseudo-class selector :- Same as CSS3 i.e. it selects every element that is not of the given element type. The only difference is in CSS3, it takes only a single selector list, where in CSS4, it takes multiple. The below will add the border to all html elements except the link.

html|*:not(:link):not(:visited) { 
    border: 1px solid black; 
}

 

Matches-any pseudo-class selector :- Match with every element, provided in the attribute list. The below example will add border to the navigation, article, section and aside of the web page.

*|*:matches(nav, article, section, aside) { 
    border: 1px solid black; 
}

 

Local link pseudo-class selector :- Matches links that point to the domain, where the current page stands for.

:local-link(0) {
    border: 1px solid black; 
}

 

Time-dimensional pseudo-class selector :- As the name suggests, matches the elements according to currently active position in some timeline. It can be applied to the document, when video is displaying its subtitle or during speech recognition of a web document. This is divided into 3 pseudo class i.e. :current, :past, :future. While reading out an web page, the below example will highlight as green color whichever text is being read aloud currently, highlight as grey color whichever has been read/will read in future.

:current(p, li) { 
    background: green; 
}

:past(p, li), :future(p, li) { 
    background: grey; 
}

 

Indeterminate-value pseudo-class selector :- Represents any checkbox/radio element whose indeterminate DOM property is set to true using javascript.

input, span { 
    background: red;
}
:indeterminate, :indeterminate + span { 
    background: yellow;
}

<input id="chk_myExample" type="checkbox" />This is an Indeterminate-value pseudo-class selector example.

document.getElementById("chk_myExample").indeterminate = true;

 

Default option pseudo-class selector :- Selects the default element among others. The below will apply green as background color to the default button among all the buttons.

:default {
    background-color: green;
}
<form>
    <input id="submit1" type="submit" /> 
    <input id="submit2" type="submit" /> 
    <input id="reset" type="reset" />
</form>

 

Validity pseudo-class selectors :- Match the elements which has its value attribute come inside/outside the specified range. It is divided into 2 selectors i.e. :in-range and :out-of-range.

input:in-range {
    background-color: green;
}

input:out-of-range {
    background-color: red;
}

 

Optionality pseudo-class selectors :- Select every form element which are optional or required.

:required {
    border: red;
}
 
:optional {
    border: grey;
}

 

Mutability pseudo-class selectors :- Selects all the elements of the page, where the contents are writable or not.

:read-only {
    border: grey;
}
 
:read-write {
    border: green;
}

 

Structural pseudo-class selectors :- It is similar to CSS3 :nth-child() selector. The only difference is before entering into the document tree, it applies the style. The below style will be applied to the second last paragraph element of DOM tree.

p:nth-last-match(2n+1) { 
    border: 1px solid black; 
}

 

Grid-Structural pseudo-class selectors :- Styles different columns of a single grid/table in a document. The below will apply background color as green for the selected/highlighted column, apply yellow as background to each second column and apply grey color to each third column of the document.

:column(.highlight) {
    background-color: green;
}
 
:nth-column(2n+1) {
    background-color: yellow;
}
 
:nth-last-column(3n+1) {
    background-color: grey;
}

 

Attribute case-sensitivity selector :- It is similar to CSS2 [attribute] selector. The only difference is case sensitivity. It match with the element exactly with the provided attribute. The first example will apply red color to the element where id can be ‘mytestclass’, ‘mytestexample’, ‘mytestset’, ‘mytestlink’. But the second example will apply the color to the element where the id exactly match with the word ‘mytestid’.

a[id~="mytestid"] { 
    color: red;
}
a[id="mytestid"] {
    color: red;
}

 

Reference combinator :- This selector consists of two slashes separating two compound attributes. The below example will apply green color to the input element, whenever its label hovered or focused.

label:matches(:hover, :focus) /for/ input { 
    color: green; 
}

 

Subject of a selector with Child combinator selector :- Generally child combinator applies the styles to the last compound selector. But here, with “Subject of a selector with Child combinator selector”, we can apply the style to the prefixed selector object. The below style will add border to the ‘ul’ element instead of ‘li’ elements.

!ul > li {
    border: 1px solid black;
}

 

Hyperlink pseudo-class selector :- Apply the style to the elements that come as the source anchor of an hyperlink. The below example will have the blue background color for all link type elements.

:any-link {
    background-color: blue;
}

 

Ohh!! That’s so much really. This time, we went through almost all the selectors of CSS and with very small and simple example. Do you really find it useful? 🙂 If yes, then please like and add some comments, if you want.

Thanks 🙂 and will be happy to listen from you 🙂 :).