The journey of #100DaysOfCode (@Darine_Tleiss)

Day01

Hello everyone :wave:, I am Darine from Lebanon MUG :lebanon: happy to join the #100DaysOfCode inspired by @henna.s, where I’ll share my daily progress learning some amazing JS stuff.

For today, the #Day1 day in this amazing journey, I’ll be sharing some amazing information about the Document Object Model in JavaScript.

What is DOM ? :thinking:

The Document Object Model is a programming interface for web documents. It represents these documents as nodes and objects, so in this case the programming language like JS can interact with the page to change the content, the style or even the structure.

DOM !== JAVASCRIPT :no_good_woman:

DOM is not a programming language, neither a part of the JavaScript language, but instead it’s a Web API used to build websites, and JS without it wouldn’t have any model of the web pages, and we as JS developers cannot make those cool animations that we see around in most of today websites. Where all of these animations are made simply by manipulating the DOM.

Dom Manipulation :face_with_monocle:

It’s the interaction process with the JS DOM API to create, modify, style, or delete elements without a refresh. It also promotes user interactivity with browsers.

DOM Tree


Let’s explore the above tree, and get to know some of it’s important parts:

  • Document: represent the entire HTML document
  • Elements: the element object represents that represent an HTML element like a ,p, div, a
  • Text: represent the tags content.
  • Attributes: represent the attributes of a specific HTML element
16 Likes

Hello @Darine_Tleiss ,

Welcome to MongoDB Community :wave: Absolutely Delighted to know that I inspired you :star_struck: This has been an amazing journey for me and I am thinking of getting back to it sometime in July now :smiley:

I wish you all the best on your self-discovery :orange_heart: and please feel free to reach out anytime when you need :smiley:

Cheers, :performing_arts:

6 Likes

100DaysofCode - Day02

Today we will explore some of the document object model functions :tada: that help us accessing different parts of our web page, or even create a new one from scratch.

First let’s explore :face_with_monocle: some of the basic DOM methods that help, retrieving and selecting certain sections of the document starting with:

  • document.documentElement
    Return the root element of the document, for example the html element for the HTML documents.

  • document.querySelector('p')
    A method that returns the first element that matches a CSS selector.

  • document.querySelectorAll('p')
    A method that returns a static NodeList representing a list of the document’s elements that match the specified group of selectors.
    Output:

    NodeList(6) [p, p, p, p, p, p]
    0: p
    1: p
    2: p
    3: p
    4: p
    5: p
    length: 6
    [[Prototype]]: NodeList
    
  • document.getElementById("section1");
    A method that returns an element with a specified value or returns null if the element does not exist.

  • document.getElementsByTagName('tagName');
    A method that returns an HTMLCollection of elements with the given tag, and the returned collection is live, meaning that it updates itself automatically And if we pass * as a tagName the method returns all the elements of the document.

  • document.getElementsByClassName('btn');
    A method that returns an array-like object of all child elements which have all of the given class name(s).

And Now it’s time, to learn more on how we can create a new element using DOM, and add some content to it : :exploding_head:

  1. const message = document.createElement('div');
    Here we are creating a div using the .createElement method and saving it to a message const.

  2. message.classList.add('greeting-message');
    In the above code, we are adding a className (greeting-message) to our newly created div with the help of classList.add method.

  3. message.innerHTML = ‘Hello dear community, I’m so happy joining this amazing journey and sharing my daily progress’ :partying_face: :partying_face:
    Here by using the .innerHTML method we are embedding some content to the created div.

  4. const body = document.querySelector('body’);
    body.append(message);
    And finally we append it to the body section of our HTML document using the following piece of code.

7 Likes

100daysofcode - Day03

Hello friends :wave:, a new day == a new progress :blush::fist:
Today we will learn how to create documents using DOM, add elements to it, prepend, append and manipulate them :rocket:

  1. Lets create a new document so we can add, remove and manipulate their elements
    let newDoc = new Document();
    Here we are initialising a new document called newDoc.

  2. Let’s create some html elements to add them to our newly created document

    let html = document.createElement(“html”);
    Here using the document.createElement function we are creating a new HTML element to be appended to our document

    newDoc.append(html)
    The .append method, add the html element to the document and the doc structure become as following:

    Now let’s expand the html element and add some new elements to it
    let head = document.createElement(“head”);
    let body = document.createElement(“body”);

    html.append(body)

    Let’s anaylze our code and see the generated document
    After creating the html document, we have created 2 new elements, the body and the head.
    And using the .append method, we’ve added the body to the html and the structure became as following:

    And now how can add the head element, before the body one ??

    Easy :sunglasses: we can simply use the .before method that inserts a set of Node or string objects in the children list of this Element’s parent, just before this Element

    So we execute it as following:

    body.before(head);

    After preparing the main document structure, let’s create some elements to be added to our body. So we can perform some experiments on them :boom::goggles:

    let h1 = document.createElement(“h1”);
    let p = document.createElement(“p”);
    let div = document.createElement(“div”);
    body.append(p,div)

    So finally let add the missing h1 element as a first child to the body.

    How ? :thinking:

    Using the body.prepend() method that inserts a set of Node objects or string objects before the first child of the Element.

    body.prepend(h1)

    Finally :partying_face: for today let’s add some text with a className ‘content’ to our paragraph, get rid of the unnecessary created h1 and move the paragraph to become the child of the empty div.

    p.innerHTML = “Hello everyone, here we are inserting some text to the p element using the write method”

    p.className = “content”
    body.removeChild(h1)
    div.appendChild(p)

5 Likes

100daysofcode - Day04

Hello friends :wave:, hope you are excited :boom: to learn something new in the amazing world of JavaScript. Today marks the 4th day in this challenging and fun journey. And Now it’s time to continue the exploration process of the DOM.

First of all we are gonna start exploring the different elements children, their parents & siblings, how we can access them and what operations we can perform on.

How can we check if a certain element has some children ? :thinking:

  1. Select the targeted element by its ID, or className as following
    const r = document.getElementById('root')

  2. After selecting it, we can easily run the following command which returns either true or false, where true means the element has some childrens and vice versa.

    r.hasChildNodes()
    true
    

    How can we list the childNodes of a certain element if they exist ? :thinking:

    Using the Element.childNodes function that returns a live NodeList of child nodes, where the first child node is assigned with index 0, and so on.

     const r = document.getElementById('root')
     r.childNodes
              
     NodeList(3) [ul#nav-access.a11y-nav, div.page-wrapper.category-api.document-page, footer#nav-footer.page-footer]
                      0: ul#nav-access.a11y-nav
                      1: div.page-wrapper.category-api.document-page
                      2: footer#nav-footer.page-footer
                      length: 3
                      [[Prototype]]: NodeList
    

    Now let’s dive into our elements and learn more about how we can access a first child, a last one, how we can change, delete them and more

    To access the first child :child:, using the Node.firstChild property that returns the first child in the tree.

     const r = document.getElementById('root')
     r.firstChild
     <ul id=​"nav-access" class=​"a11y-nav"> ​… <​/ul>
    

    To access the last child :child:, using the Node.lastChild that returns the last child of the node

    const r = document.getElementById('root')
     r.lastChild
     <footer id=​"nav-footer" class=​"page-footer"> …​ </footer>
    

    To access an element at a certain position we can access it simply by specifying it index, using the Element.children[index]

    const r = document.getElementById('root')
    r.children[1]
    <div class=​"page-wrapper category-api document-page"> ​…​  </div​>
    

    To delete a certain child :child:, we can use the removeChild() method that returns the specified child if it exists from the DOM then returns it.
    Example:

    const r = document.getElementById('root')
    r.removeChild(r.children[0])
    <ul id=​"nav-access" class=​"a11y-nav"> ​… </ul> ​
    

    And here the first child with the index 0 is removed from the tree and the new set is:

     HTMLCollection(2) [div.page-wrapper.category-api.document-page, footer#nav-footer.page-footer, nav-footer: footer#nav-footer.page-footer]
               0: div.page-wrapper.category-api.document-page
               1: footer#nav-footer.page-footer
               nav-footer: footer#nav-footer.page-footer
               length: 2
               [[Prototype]]: HTMLCollection
    

    Moving from childrens to parents & siblings. Let’s now learn more about them, how to access some of them and more …

    To access the parent :family_man_woman_boy:of a certain element we can simply use the following property Element.parentNode, which return the parent of the targeted element as following:

    const r = document.getElementById('root')
    r.parentNode
    <body> …​ </body>​
    

    To access the siblings :people_holding_hands:of a certain element, we have to use the basic properties of the Node.nextSibling that return the next sibling in the tree and the Node.previousSibling that return the previous one.
    Example:

    const element = document.getElementById('p2')
    element.previousSibling
    <div class=​"page-footer-nav-col-1" id=​"p1"> ​… </div​>
    element.nextSibling
    <div class=​"page-footer-nav-col-3" id=​"p3"> ​…​ </div​>
    
6 Likes

100daysofcode - Day05

Hey everyone :wave:, what is going on ??. Today marks the 5th day in our coding challenge.
In Today post we will make a gentle dive in the document object model events, their types and how we can deal with them.

What are the HTML DOM events ? :thinking:
Events that allow the JavaScript programming language to add different event handlers on HTML elements. They are a combined with callbacks functions where these functions will only execute if the specified event occur.

Examples of HTML DOM events:

  • Loading a webpage
  • Loading an image into the browser
  • When an input field is changed
  • On User keystrokes
  • On form submission

And now let’s explore some of the basic events in JavaScript.

  • The load and onload event, that gets fired when the whole page loads, including all the dependencies resources like the external images, stylesheets …
    Example:

    window.addEventListener('load', (event) => {
    console.log('The entire page and its dependencies is fully loaded');
    });
    
  • The unloaded event is fired when the document or one of its child gets unloaded, it typically execute when the user navigate from one page to another, and this type of events can be used to clean up the references to avoid memory leaks
    Example:

    window.onunload = (event) => {
          console.log('The page is unloaded successfully');
      };
    
  • The onchange event, that get fired when a user commit a value change to a form control
    Example:

    // A function to count the user message length
    function countUserMessageLength(e) {
    console.log(e.target.value.length)
    }
    // Select the input element
    let input = document.querySelector('input');
    // Assign the onchange eventHandler to it
    input.onchange = handleChange;
    
  • The mouseover event, that gets fired at an Element when a pointing device (such as a mouse) is used to move the cursor onto the element or one of its child elements.
    Example:

    <ul id="list">
      <li>Javascript</li>
      <li>MongoDB</li>
    </ul>
    
    let list = document.getElementById("list");
    
    list.addEventListener("mouseover", function( event ) {
    	// on mouseover change the li color
    	event.target.style.color = "orange";
      
    	// reset the color after 1000 ms to the original
    	setTimeout(function() {
    	  event.target.style.color = "";
    	}, 1000);
      }, false);
    
  • The onpaste event, gets fired when the user has initiated a “paste” action through the browser’s user interface.
    Example:

    <div class="source" contenteditable="true">Copy from here ... </div>
    <div class="target" contenteditable="true">...and pasting it here</div>
    
    const target = document.getElementByClassName("target")
    
    target.addEventListener('paste', (event) => {
       let paste = (event.clipboardData || window.clipboardData).getData('text');
       paste = paste.toUpperCase();
     
       const selection = window.getSelection();
       if (!selection.rangeCount) return false;
       selection.deleteFromDocument();
       selection.getRangeAt(0).insertNode(document.createTextNode(paste));
     
       event.preventDefault();
    });
    
6 Likes

100daysofcode - Day06

Hello friends :star_struck:, hope your journeys are going smoothly. Today marks the 6th / 100 day. Let’s learn something new in Javascript and make our journey a successful one .:white_check_mark::boom:

Today, we will continue discovering some new HTML DOM events, and how we can use them to manipulate our document and make some amazing effects.

  • The scroll :scroll: event, that fires when the document view has been scrolled.
    Example:

    let positionTracker = 0;
    let ticking = false;
     
    function doSomething(scrollPos) {
     // Do something with the scroll position
    }
     
    document.addEventListener('scroll', function(e) {
     positionTracker = window.scrollY;
     
     if(positionTracker > 1500) {
       alert("OH we reached the second half of our website")
     }
     
     if (!ticking) {
       window.requestAnimationFrame(function() {
         ticking = false;
       });
     
       ticking = true;
     }
    });
    
  • The toggle event, or ontoggle event that gets fired when the open / closed state of a <details> element is toggled.
    Example:

    <aside id="log">
     <b>Open chapters:</b>
     <div data-id="ch1" hidden>I</div>
     <div data-id="ch2" hidden>II</div>
    </aside>
    <section id="summaries">
     <b>Chapter summaries:</b>
     <details id="ch1">
       <summary>Chapter I</summary>
        MongoDB is the powerful NoSQL database
     </details>
     <details id="ch2">
       <summary>Chapter II</summary>
         Javascript is one of the most popular programming languages.
     </details>
    </section>
    <script>
    function logItem(e) {
       const item = document.querySelector(`[data-id=${e.target.id}]`);
       item.toggleAttribute('hidden');
     }
      const chapters = document.querySelectorAll('details');
     chapters.forEach((chapter) => {
       chapter.addEventListener('toggle', logItem);
     });
    </script>
    
  • The offline :mobile_phone_off: event, that gets fired when the browser has lost access to the network and the value of Navigator.onLine switches to false
    Example:

    window.addEventListener('offline', (event) => {
       console.log("The network connection has been lost.");
    });
     
    // onoffline version
    window.onoffline = (event) => {
     console.log("The network connection has been lost.");
    };
    
  • The wheel :wheel: event fires when the user rotates a wheel button on a pointing device
    Example

    <div>Lets scale with the mouse wheel.</div>
     
    const element = document.querySelector('div');
    let scale = 1;
    function zoom(event) {
       event.preventDefault();
        scale += event.deltaY * -0.01;
        element.style.transform = `scale(${scale})`;
     }
     element.addEventListener('wheel', zoom);
    
  • The reset event fires when the html element is resetted
    Example:

    const form = document.getElementById('form');
    const log = document.getElementById('log');
     
    function logReset(event) {
       log.textContent = `The Form has been reseted! Time stamp: ${event.timeStamp}`;
     }
     
    form.addEventListener('reset', logReset);
    
6 Likes

100daysofcode - Day07

Hey friends, Today is the 7th day of our amazing journey. I hope everyone enjoying their journey and learning some amazing things :boom::tada:.

In Today’s post, we will take a break from Javascript :smiling_face_with_tear:, and move on to learn and discover CSS, and its role in building stunning Web interfaces :heart_eyes::rocket:.

So, starting with a quick introductory question :sunglasses::face_with_monocle:, What does CSS stands for ?? :thinking:

What CSS is all about in simple terms ?

A standard that describes the formatting of markup languages pages, CSS describes how elements should be rendered on screen, on paper, in speech, or on other media. It define the formatting rules for the following document types:

  • HyperText Markup Language (HTML)
  • Extensible HyperText Markup Language (XHTML)
  • Extensible Markup Language (XML)
  • Scalable Vector Graphic (SVG)
  • XML User Interface Language (XUL)

The C in CSS
The process of combining different stylesheets and resolving conflict between different CSS rules and declarations, when more than one rule applies to a certain element.

A gentle look to CSS behind the scene :eyes::face_with_monocle::mag_right:

How can we apply CSS rules to an HTML document ?

In CSS we have three different methods to apply css to an html document.

  • External stylesheets
  • Internal stylesheets
  • Inline styles
  1. External stylesheets
    An external stylesheet containing the css rules separated in a file with a .css extension. This most common and useful method of adding CSS to a document, where we can link a single css file to multiple web pages, styling all of them with the same stylesheet. And we link the HTML page with the CSS sheet simply by using the link element, and specifying the path of the css file in the href attribute.
    Example:

    File 1: index.html

    // index.html file
    <!DOCTYPE html>
    <html>
     <head>
       <meta charset="utf-8">
       <title>Css External file</title>
       <link rel="stylesheet" href="styles.css">
     </head>
     <body>
       <h1>Hello World!</h1>
     </body>
    </html>
    

    File 2: styles.css

    // style.css file
    h1 {
       color: blue;
       background-color: yellow;
       border: 1px solid black;
     }
    
  2. Internal Stylesheets
    The internal stylesheet live within the HTML document, and we can simply creating it by placing our css inside a element in the head of our HTML document.
    Example:

    <!DOCTYPE html>
    <html>
     <head>
       <meta charset="utf-8">
       <title>Internal StyleSheets</title>
       <style>
         p {
           color: blue;
           font-size: 12px;
         }
       </style>
     </head>
     <body>
     
       <p>Hello folks, in today post we are exploring css basics,
       by doing a gentle tour on its basics
       </p>
     </body>
    </html>
    
  3. Inline Style
    CSS declarations that affect a single HTML element, contained with a style attribute.
    Example:

    <!DOCTYPE html>
    <html>
     <head>
       <meta charset="utf-8">
       <title>Css Inline Style</title>
     </head>
     <body>
       <p style="color:blue;">I love learning CSS</p>
     </body>
    </html>
    
5 Likes

100daysofcode - Day08

Hello family, hope you’re enjoying my daily posts :roll_eyes::smiling_face_with_three_hearts: . Let’s continue, and celebrate our daily progress :100::v:. Today marks the 8th day / 100. And in today’s post, we will dive more in CSS and learn some amazing new things. :boom::tada:

First of all, we will discover :mag_right::thought_balloon: what selectors are and how we can use them in our CSS document.:page_facing_up::scroll:

What is a CSS rule set ? :thinking::thinking:

A CSS rule set contains one or more selectors and one or more declarations. The selector(s), which in this example is the class .my-css-rule , points to an HTML element. The declaration(s), which in this example are background: red; color:beige; font-size: 1.2rem

What is a CSS selector ?

A CSS selector is the first part of a CSS Rule. It is a pattern of elements and other terms that tell the browser which HTML elements should be selected to have the CSS property values inside the rule applied to them.

Example:

h1 {

color: blue;

text-align: center;

}

In the above css rule, the selector is simply the h1 element, and the selector can be an HTML element, a class, an ID …

We can also combine more than selector in the same css rule as follows.

h1, .container {

color: blue;

}

In the above example, the css rule contains 2 different selectors, an h1 element, and a class called container.

Type of selectors:

  • Universal selector: Known as wildcard, that matches any element

    The defined selector, below will affect all html elements, to have a color of red and a font size of 14 pixels

    Example:

    * {
    
    color: red;
    
    font-size: 14px;
    
    }
    
  • Class selector: each HTML element can have one or more items defined in their attribute. The class selector matches any element that has the class applied to it.

    Classes in css start with a dot , example: .cssclass

    index.html

    <p class="cssclass"></p>
    
    <div class="cssclass"></div>
    

    styles.css

    .cssclass {
    
    color: blue;
    
    }
    
  • ID selector: each HTML element can have an ID, and this ID should be unique to only one element in the page

    The ID in the css, is represented with a #

    index.html

    <p id="cssID"></p>

    styles.css

    #cssID {
    
    color: blue;
    
    font-size: 2rem;
    
    }
    
  • Attribute selector

    The CSS attribute selector matches elements based on the presence or value of a given attribute. Instruct CSS to look for attributes by wrapping the selector with square brackets ([ ]).

    Example:

    index.html

    <div data-type="primary"></div>

    styles.css

    [data-type='primary'] {
    
    color: red;
    
    }
    
  • Grouping selector

    A selector doesn’t have to match only a single element. You can group multiple selectors by separating them with commas

    Example:

    h1,
    
    #cssID,
    
    .my-class,
    
    [lang] {
    
    color: red;
    
    }
    
8 Likes

Yes, we are enjoying your posts! :slight_smile:

3 Likes

Hi @Darine_Tleiss,

Thank you for continuing to share such informative posts – definitely enjoying the daily read and following your learning journey :raised_hands:

Regards,
Stennie

4 Likes

100daysofcode - Day09

Hello community, hope everyone is doing well :boom::smiling_face_with_three_hearts:. The 9th day is here, and some :new: knowledge are required before marking the day as completed :white_check_mark:

In today’s post, we will dive :diving_mask: more into CSS, exploring some amazing features :world_map:, and expanding our existing knowledge. :tada:

What is the Cascade in CSS ? :thinking::innocent:

  • Cascade is an algorithm that defines how the user agent combines properties from different sources. And how it solves :relieved: the conflict :exploding_head: when multiple CSS rules apply to an HTML element.

  • It lies at the core of CSS, and simply when a selector matches an element :white_check_mark:, the property that comes from the origin with high precedence gets applied :hugs:.

How does the Cascade algorithm work ? :flushed:

  The defined algorithm, is splitted into :four: different stages :wink:

  1. Position and order of appearance: the order in which your CSS rules appear

  2. Specificity: the algorithm that determines which CSS selector has the strongest :muscle: match

  3. Origin ⌱: the order of when CSS appears and from where it comes from ( user-agent, author, user stylesheets)

  4. Importance :sunglasses:: the css rule, with a heavy weight than others (especially the one marked with !important)

What are the origin types in CSS ?

  • As we know, the cascading algorithm job :woman_mechanic: is to select CSS declarations in order to determine the correct :heavy_check_mark: values for CSS properties. These declarations comes from different ↔ origins
  • The origin types are: User-agent stylesheets, Author stylesheets, User stylesheets :sleeping:

    User-agent stylesheets :robot:

  • Agents or browsers have some basic style sheets that give the document a default style. And these sheets are called user-agent stylesheets.

    Author stylesheets :writing_hand::woman_teacher:

  • The stylesheets written by the web developers :man_technologist: or the web designers :art:
  • Such type of stylesheets can be used to reset :wastebasket: the agent style
  • The author can define these styles using ❶ or more linked stylesheets like the blocks, the inline styles, or the imported css files

    User stylesheets :woman_technologist::man_technologist:

  • An assistive way that allow the end users of a certain website, to customize its display :tv: to fit with their needs by overriding :pencil2: the author styles
  • User stylesheets can be configured directly and embedded to the website or added via 3rd parties browsers extensions

What is CSS Specificity ?

  • An algorithm used by the agents to determine the winning :1st_place_medal::trophy: CSS rule to be applied to the HTML element. Where this element have two or more rules pointing to it
  • Specificity Hierarchy
  1. Inline styles
    Example <p style=”color:red”;> Hello </p>

  2. ID’s
    Example: #paragraphStyle {color: red}

  3. Classes, pseudo-classes, and attribute selectors
    Example: .paragraphStyle, :hover, [href]

  4. HTML elements, and pseudo elements
    Example: p, h1, :before, ::after

  • Inline style has the highest :chart_with_upwards_trend: specificity and they always win :trophy:, except the case when we use the !important rule :sob: that can override them.

How can we calculate the CSS Specificity ?

  • We give the ID’s a specificity value of :100:

  • We give the Classes a specificity value of :keycap_ten:

  • We give the HTML elements a specificity value of ❶

  • We give the inline styles a specificity value of 1000

  • Example:

    A: p {color: red; }
    
    B: p#content {color: yellow; }
    
    C: <p id="content" class=”paragraphContent” style="color: blue;">Hello World</p>
    
    D: p.paragraphContent { color: green; }
  • For A, we have 1 (for the HTML element) :sob:

  • For B, we have 101 (1 for the HTML element and 100 for the ID ) :face_holding_back_tears:

  • For C, we have 1000 (for the inline style) :sunglasses::trophy::tada:

  • For D, we have 11 (1 for the HTML element, and 10 for the Class) :smiling_face_with_tear:

If we compute the results quickly we can see that the winning :trophy: specificity is the one related to the inline style, and in this case the browser applies the css defined in the inline rule.

6 Likes

100daysofcode - Day10

Day :keycap_ten:, is already here :tada:, Hello folks, how are your journeys going ? :smiling_face_with_three_hearts: Let’s continue our learning journey and dive more into some new topics in the amazing world of CSS. :new::pencil2:

*In today Post, we will talk more about inheritance :fist:, an important topic in CSS​:flushed:, then we will move to discover the inherit, initial, keyword and how we can use them to control the inheritance process.*:sunglasses::fire:

So What does the term inheritance mean ? :thinking:

  • In computer science :desktop_computer:, inheritance is a mechanism in which one class acquires the property of another class. For example, a child :child: inherits the traits of his/her parents. :family_man_man_boy:

What does the CSS inheritance mean ? :art:

  • In CSS, inheritance controls what happens when no value is specified for a property on an element. Where the rulesets in CSS cascade down the hierarchy :handshake:, from the parent to the children selectors.
  • Example
    <html>
       <head>
           <title>Inheritance in CSS</title>
           <style>
               #parent{
                   color: blue;
                   font-weight: bold;
               }
           </style>
       </head>
       <body>
           <div id="parent">
               This is the parent
               <div id="child1">
                   This is the first child
               </div>
               <div id="child2">
                   This is the second child.
               </div>
           </div>
          
       </body>
    </html>
  • Result

  • In the previous example we have ⒉ child :girl::child: div’s, wrapped inside a parent div, each of them have a unique ID, and as we can see in our example, when the parent div got some CSS :art:rules like color: blue, and font-weight: bold, these css rules affected the child divs directly. And with a quick inspection :mag: to our webpage we can see clearly that the css rules get inherited from the parent, as demonstrated in the below image.

  • Here we can see that the CSS rules defined by the user-agent are disabled :x: and the parent style rules get applied.

Can all CSS properties get inherited ?? :thinking:

  • No :no_good_woman:, in simple words not :x: all CSS properties can be inherited from their parents elements.
  • Let’s list some of the CSS inherited properties
    1. font-* (like font-size, font-family, font-weight …)
    2. text-align , text-indent, text-transform
    3. color
    4. border-spacing …

How can we inherit a non-inheritable property in CSS ?

  • To inherit a non-inheritable property, we can simply use the CSS inherit keyword on the targeted property.
  • So let’s make an example to demonstrate how the inherit keyword work with a non-inheritable property like the hight or the width
  • Example
    <html>
       <head>
           <title>Using the inherit keyword</title>
           <style>
               #parent{
                 border: 3px solid black;
                 margin-bottom: 10px;
               }
               #child2{
                   border: inherit;
               }
     
               #child1{
                   margin-bottom: inherit;
               }
     
           </style>
       </head>
       <body>
           <div id="parent">
               This is the parent
               <div id="child1">
                   This is the first children
               </div>
               <div id="child2">
                   This is the second children.
               </div>
           </div>
          
       </body>
    </html>
  • As we can see in the result shown above, the child2 inherited the border property from its parent . At the same the child1 inherited the margin-bottom property as specified. And here we can say that using the inherit keyword, any non-inheritable property can be used and inherited on demand.

The initial value ? How it works, and how we can use it ?:flushed::thinking:

  • The initial CSS keyword applies the initial (or default) value of a property to an element. It can be applied to any CSS property, including the CSS shorthand property all
  • Example
    <html>
       <head>
           <title>Using the initial keyword</title>
           <style>
               #parent{
                 color: red;
               }
               h1 {
                   color: initial
               }
           </style>
       </head>
       <body>
           <div id="parent">
              <h1> Hello from the h1 tag</h1>
              Here some normal lorem ipsum text.
           </div>
       </body>
    </html>
  • Result:

  • As we can see in our example :boom:, the div with the id parent get the color:red applied to its lorem ipsum content, but the h1 tag was not affected at all. Why? Simply because we are using the initial keyword on it. Which give it the initial color property from the user-agent style and not the inherited one from it’s parent.

6 Likes

100daysofcode - Day11

Hello friends :wave: :smiling_face_with_three_hearts:, a new day is here, and today marks the 11th :partying_face: day from my amazing learning journey. So let’s dive more into CSS and discover all the amazing features that CSS provides us on the fly to build such amazing web interfaces :boom:.

Starting our post, we will talk about colors :rainbow:, their types and how CSS deal with them to apply the corresponding value added to each property.

Where and how the CSS colors are applied ? :face_with_monocle:

  • Colors are an essential part of any modern software, that aim to interact with users in a smooth way, and CSS has many options for color types, so let’s start exploring them one by one and learn more how to deal with each type of them. :thinking:
  1. Color keywords:

    • In CSS we have a list of around 148 named colors. These colors are written in plain english and have meaningful descriptions so they can be used in the correct place to give the correct result.
      Example: blue :blue_heart:, red :hearts:, white :white_heart:, salmon​:two_hearts:, royalblue​:blue_heart:, lightgreen​:green_heart:.

    • Alongside to these named colors we have other special keywords that can be used, like:

      1. Transparent: a fully transparent color, that is mainly used as an initial value for background colors.
      2. CurrentColor: a dynamic computed property that takes the color value from an existing one. For example we have a text color set to be blue and we assign the border-color, the value of current it will take also a blue color value as the one with the text.

    Example:

    <html>
     <head>
      <title>Using Current Color</title>
       <style>
    div {
     padding: 10px;
     color: royalblue;
     border: 4px solid;
     border-color: currentColor;
    }
     </style>
    </head>
     <body>
      <div>
        Hello world
      </div>
     </body>
    </html>
    

    Result

    And here we can see that the border-color currentcolor is set automatically to royal blue which is the text color that we defined previously.

  2. Numeric colors:

    • The basic building blocks of a color in CSS, where any developer can deal with colors using their numeric values, like the hexadecimal colors, the hexadecimal colors with alpha, the RGB and finally the HSL colors.

    • Hexadecimal colors.

    • A color hex code is a hexadecimal way to represent a color in RGB format by combining three values – the amounts of red, green and blue.

    • Hexadecimal numbers have a range of 0-9 and A-F , where 10 is A, 11 is B, 12 is C …, and when we use the six digit sequence they got translated to RGB numerical ranges, where the six digits are divided sequentially on the 3 colors (2 → Red, 2 → Green, 2 → Blue)

    Example (the first 2 values represent the amount of red, the second 2 the green and the last 2 the blue) where this combination give us the shown color below.

    • Hexadecimal colors with alpha.

    • The hexadecimal part, stay the same and the alpha value is simply a numeric value that define the percentage of transparency.

    • When adding a transparency percentage the sequence becomes eight digits instead of 6, where the last 2 digits represent this transparency level.

    • O alpha is represented with 00.

    • 50% alpha is represented with 80.

    • 75% alpha is represented with BF.

    Example:

    • RGB (Red, Green, Blue) colors.

    • The RGB color model is an additive color model in which the red, green, and blue primary colors of light are added together in various ways to reproduce a broad array of colors.

    • Colors combinations can be set as numbers in a range of 0-255 inside the rgb() function.

    Example: rgb(183, 21, 64);

    • These combinations can be set as percentages in a range between 0% and 100% also inside the rgb() func.

    Example: rgb(25%, 31%, 39%);

    • As hexadecimal numbers in RGB we can also use alpha to set the level of transparency and the function become rgba instead of rgb.

    Example: to add a 50% transparency we can set the color values in the rgba functions as follow

    rgba(0, 0, 0, 50%) or rgba(0, 0, 0, 0.5).

    • HSL (Hue, Saturation, Lightness) colors.

    • Hue: is a degree on the color wheel from 0 to 360, where 0 is red, 120 is green and 240 is the blue.

    • Saturation: can be described as the intensity of a color, where 100% means that we are dealing with pure color, without any shades of gray. 50% have 50 shades of gray. And 0 a complete gray.

    • Lightness: specify the amount of light we want to add to the color. Where 0% means no light, and 100% means full light.
      Example:

    • HSLA: the normal hsl() with a 4th parameter to represent the transparency level.
      Example:
      hsla(0, 100%, 50%, 0.5)
5 Likes

100daysofcode - Day12

Hello everyone :smiling_face_with_three_hearts:, hope your day was a productive and a fun one :boom:. Today marks our 12th day from this amazing journey :star_struck:. And now let’s wrap it up with some new and important topics.

In today’s post, we will discover what SASS / SCSS is all about, how it differs from the normal CSS and what are the extra capabilities that SCSS gives us out of the box.

Be ready to learn some new and in demand information, and please enjoy your day to the maximum. :tada:

What is SASS ? :thinking:

  • Moving from normal CSS, now let’s dive into a new amazing topic that extends the capabilities of CSS. YEAH I’m talking about SASS, the famous CSS preprocessor, that extend the normal CSS :smiling_face_with_tear: and add a lot of power :battery:and elegance :star_struck:to it.
  • SASS stands for :thinking:: Syntactically Awesome :heart_eyes:Style Sheets.

How does SASS extend CSS ? :face_with_monocle:

  • A powerful extension that enables us to use variables, nested rules, inline imports, mixins, functions and more out of the box to make CSS a hero for every front end developer.
  • SASS reduces repetition, and saves a lot of time by enabling developers to write reusable pieces of code via variables, mixins and functions…

What is SCSS ? :face_with_peeking_eye:

  • SCSS: Stands for Sassy Cascading Style Sheets.
  • Sassy CSs was introduced as the main syntax for the SASS, which builds on top of the existing CSS syntax.
  • It makes use of semicolons and brackets like CSS where we can say it’s a superset of CSS and it contains all the features available in both CSS and SCSS.

SCSS vs. SASS – How they differ in terms of syntax.

image

How does SCSS/SASS work ? :face_with_raised_eyebrow:

  • Any modern browser does not understand SCSS nor SASS on the fly. So we need a preprocessor to convert such kind of code to a standard CSS that every browser can deal with.
  • This conversion process is called transpiling, where the transpiler translates them into normal CSS.

SCSS Architecture ? How is SCSS organized behind the scenes ?? :face_in_clouds:
First of all let’s start by understanding the Think-Build-Architect mindset.

  • Think ? :eyes:: we should think about the layout of the webpage, or web app before writing the code

    1. Modular building blocks that make up interfaces.

    2. Held together by the layout of the page.

    3. Reusable across a project, and between different projects.

    4. Independent, allowing us to use them anywhere on the page.

  • Build ? :building_construction:: we should build the HTML layout, alongside with the CSS following a consistent structure for classes naming.
    Here we should use the BEM methodology.

    • BEM ?: Block Element Modifier.
      • Block ?: a standalone component that is meaningful on its own.

      • Element?: a part of the block, that has no standalone meaning.

      • Modifier?: a different version of a block or an element.

And now we have reached the end of this long and informative post :partying_face:, I hope you will enjoy exploring these amazing new topics in the world of CSS / SCSS and SASS. Stay tuned for tomorrow’s post where we will dive together in the 7-1 pattern which plays an important role in architecting every production SCSS project out there :dizzy:.

5 Likes

100daysofcode - Day13

Hello friends, How it’s going on :smiling_face_with_three_hearts:, wrapping up our 13th day successfully with some amazing content. And a deep dive :diving_mask: into SASS and SCSS.

In yesterday’s post, we defined SCSS and SASS, how they extend the CSS capabilities giving us a lot of features out of box :star_struck::smiling_face_with_three_hearts:, making the front end developers life a smooth :hugs: and productive one :muscle:. We also mentioned the SCSS architecture :construction_worker_woman:, with a gentle intro about the thinking and building phase. And now it’s time to resume :play_or_pause_button: our process and talk more about the 3 and the most important phase. The (Think Build Architect) 3rd parameter.

YEAH, You guessed it !!. The Architect phase :heart_eyes::blush::sunglasses:

  Architect ?: In this phase we should create a logical architecture to organize our CSS files
 and folders.
  And here we follows the famous 7-1 pattern :thinking::star_struck:

  • 7-1 pattern ?: A famous :sunglasses: and well adopted structure that serves as a solid base for large :partying_face:and production projects. In this :seven:/:one: arch we have 7 different folders for partial SCSS files and a single :smiling_face_with_tear:file that sits at the root, we usually call it the main file, where all files are imported to be compiled into a compatible CSS stylesheet :white_check_mark:

How does the seven/one pattern organize the folders and files in SCSS ? :thinking:

  Starting with folders, we will explore each one of them in deep details, starting with:

  1. Base: the folder that hold the boilerplate :curry: code of the project, including all standard styles, like the typographic rules, which they are used :repeat: commonly throughout the project :sunglasses:
    Example:

            	base/
                      _animations.scss
          			  _typography.scss
          		      _ base.scss(contains the html and body components)
    
  2. Components: the folder that hold the style of the sliders, buttons, and all similar :tada: components like the reusable widgets in React JS :grinning::nerd_face:
    Example:

    		  components/
    				_button.scss
    				_form.scss
                    _popup.scss
    
  3. Layout: the folder that contains the styles files that control the project layout :artist:, like the styles of the navigation bar, the header, the footer :end::no_mouth:
    Example:

    	  layout/
    		_footer.scss
    		_navigation.scss
    		_header.scss
    
  4. Pages: the folder that contains the specific style of an individual :man_technologist::smiling_face_with_three_hearts: page, like the home page style. Which is not :x: required in other pages and at the same time does not 🆇 require any style from other pages.
    Example:

        	 pages/
                _home.scss
    
  5. Themes: a folder that contains the files of specific themes, and it’s not used in every :repeat: project out there :earth_africa:, as it only required if we have some sections the contain alternate schemes :art:
    Example:

    	   themes/
    		    _theme.scss
    		    _admin.scss
    
  6. Abstracts: the folder that contains the helper :rescue_worker_helmet: files, mixins functions, SASS tools :gear: and any other config file :wrench:, and this files are just helpers which don’t output when they get compiled :roll_eyes:
    Example:

           abstracts/
    	       _functions.scs
    	       _mixins.scss
    	       _variables.scss
    
  7. Vendors: the folder that contains all third :3rd_place_medal: party code and all external libraries​:books:, like bootstrap, jQuery, tailwind …
    Example:

    	   vendors/
    	     	_bootstrap.scss 
    	    	_jquery-ui.scss
    

  So yeah, now we explored :world_map: our :seven: folders successfully :white_check_mark:, so let’s move on and explore the single file that exists in the amazing architecture. :slightly_smiling_face:

  1. main.scss: the file that only :sob: contains the required imports from all :muscle: other files.:innocent:
    Example:

        
            @import "abstracts/functions";
            @import "abstracts/mixins";
            @import "abstracts/variables";  
               
            @import "base/animations";    
            @import "base/base";  
            @import "base/typography";    
            @import "base/utilities";    
               
            @import "components/bg-video" ;  
            @import "components/button";  
            @import "components/card";
            @import "components/composition";
            @import "components/feature-box";
            @import "components/form";
            @import "components/popup";
            @import "components/story";
                   
            @import "layout/footer";
            @import "layout/grid";    
            @import "layout/header";
            @import "layout/navigation";
             
            @import "pages/home";
    

And now, we have reached the end of our post. I hope you enjoyed :face_with_hand_over_mouth: reading it and benefited from it. Stay tuned for my ⎘ next posts where we will learn together :muscle: how we can install :computer: SASS and SCSS, via the node package manager and start exploring it in an interactive way :tada::smiling_face_with_three_hearts::star_struck:

5 Likes

100daysofcode - Day14

Hello everyone, day 14 is already here, let’s move on and make some daily progress toward the success goal. Yesterday we discovered the :seven: / :one: architecture that makes our work with such kinds of front end apps a smooth one.
In today’s post, we will move on from the theory part, to learn more about how to install SCSS in your next front end project. What are the requirements and how can we get the project running ?

SCSS on your hello world project :tada::fist:
In the modern web development stacks, the node package manager (npm), plays an important role in making our life an easy one. With a simple command we can install one of a million available packages that give us the required features out of the box and for free.

How can we install NPM ? :thinking:
To install the node package manager and use it in your next project, first of all you should visit the official documentation of nodejs (which runs JS on the server on simple terms). And install it based on your machine type.
Nodejs link: Download | Node.js

What should we do after installing node js locally on our machine ? :eyes:
First of all to make sure that everything in your setup, is completed correctly and to move on smoothly to the next phase, please run the following 2 commands on your terminal, to test if node js and npm gets installed correctly

  1. Test NodeJS
    node --version
    Which should return a certain version like v17.0.1 in my case

  2. Test npm
    npm --version
    Which should return a certain version like v8.1.3
    in my case

How to install SCSS in a new clean project ? :face_with_monocle:

  1. First of all please visit your favorite location, in the local machine and create a new directory under the name helloFromScss.

  2. Navigate to the newly created folder, and open it with your favorite editor (in my case i’m using vs-code).

  3. Open the terminal inside your project, and at the root level perform the following command : npm init --y.

    • The npm init command initializes a project and creates the package.json file. And when adding the --y, we are simply skipping the interactive questions process that ask for example for the author name and other information.
      Output: package.json

       {
         "name": "hellofromscss",
         "version": "1.0.0",
         "description": "",
         "main": "index.js",
         "scripts": {
         },
         "keywords": [],
         "author": "",
         "license": "ISC"
       }
      
    • Let’s analyze the package.json file :face_with_peeking_eye:: in simple terms this generated file plays an important role in building the project where it contains some metadata about it. Like the name of the project and it’s description and other functional requirements like the list of dependencies and installed npm packages which are required by our application to run properly.

  4. Now our empty project is ready :star_struck:, the package.json file is generated and all the required setup is done. So it’s time to install sass in our project using this simple command: npm install node-sass or npm i node-sass.

    The npm install installs all modules that are listed on package. json file and their dependencies.
    And now the package.json file becomes as follow:

    {
     "name": "hellofromscss",
     "version": "1.0.0",
     "description": "",
     "main": "index.js",
     "scripts": {
       "test": "echo \"Error: no test specified\" && exit 1"
     },
     "keywords": [],
     "author": "",
     "license": "ISC",
     "dependencies": {
       "node-sass": "^7.0.1"
     }
    }
    
4 Likes

100daysofcode - Day15

Hello friends :wave:, a new day is here. Let’s wrap the 15th day from this amazing 100 day journey. :smiling_face_with_three_hearts::muscle:

In yesterday’s post, we explored :world_map: how to install :arrow_down: nodeJS, with the node package manager that helps us starting a :new: project and install all the requirements to use and manipulate sass code. :star_struck:

In today’s post, we will start diving :diving_mask: in some amazing topics that show us clearly the power :battery: of sass and how this powerful extension to the normal css helps us write efficient code, reusable and non redundant one. :sunglasses::heart_eyes:

We will start by exploring the variables concept in Sass, how we can define a new variable, set a value for it and use it in the entire file.

What are sass variables ? :thinking:

  • In simple terms we can say that a variable is a container :jar: that holds a certain value in a specific scope :hugs: . In Sass we can simply create a new variable by adding a $ sign followed by the var name, and then we can refer to the defined name instead of repeating :sob: the same value in different places.

  • Variables are one of the most useful tools :tada: that help developers reduce repetition, do complex math, and even configure libraries.

  • Sass variables are all compiled away by Sass :grinning:

  • Sass treats variables in an imperative way, which means if we use a variable then we change its value later on in the project. The earlier use will stay the same :zzz:. Which differ from the normal css approach which treat it’s variables in a declarative way where any change to the var value affect all uses :rage:

  • In Sass, we have some built in variables which get imported from 3rd parties modules. And such variables cannot :x: be modified in terms of value.

  • In Sass, all underscores and hyphens are treated the same,:smiling_face_with_tear: for example if we have a variable called (font_size) and another one called (font-size). The Sass compiler treat them as one same variable
    Example : 1 :muscle:

    // Here we are defining some color variables
    $color-primary: #c69963;
    $color-primary-dark: #b28451;
    $color-secondary: #101d2c;
    $color-grey-light-1: #f9f7f6;
    $color-grey-dark: #54483a;
     
    // And now some font variables gets defined
    $font-primary: "Nunito", sans-serif;
    $font-display: "Josefin Sans", sans-serif;
     
    // For example, here in the body rule instead of adding
    // the font family and color values again
    // we just call them using their names
    body {
     font-family: $font-primary;
     color: $color-grey-dark;
     font-weight: 300;
     line-height: 1.6;
    }

Example : 2 - Use a built in variable is Sass :tada:

   /* import the math library using the @use syntax */
  @use "sass:math" as math;  
  /* use the available variables in the math library for example */
  math.$pi  // Output: 3.1415926536
  math.$e; //  Output: 2.7182818285

Variables Scope in Sass

  • First of all let’s start by understanding what a scope means in general. We can define the scope in simple terms as the part of the program where the association of the name to the entity is valid. Scope helps prevent :boom: name collisions; it allows the same name to refer to different objects - as long as the names have separate scopes :raised_hands:

  • In Sass the variables declared at the top of the stylesheet are global :earth_africa:, which means that they can be accessed anywhere :globe_with_meridians: in their module after the declaration phase. On the other hand :raised_hand: the var’s defined in blocks (inside curly braces in SCSS) are local and they can only be accessed within the block in which they were declared. :smiling_face_with_tear:
    Example : 3

    $global-variable: global value;
     
    .content {
     $local-variable: local value;
     global: $global-variable;
     local: $local-variable;
    }
     
    .sidebar {
     global: $global-variable;
     
     // This would fail, because $local-variable isn't in scope:
     // local: $local-variable;
    }

Variables shadowing in SASS ❏💭

  • When a local variable is defined with the same name as a :earth_africa: already defined one. In this :clapper: we have 2 identical variables in terms of their name. One local and one global. :handshake:

  • If we need to set a global variable value from the local scope like a mixin, we can use the **!global** flag :triangular_flag_on_post:, where any variable assigned with such flag gets its value from the global scope.
    Example : 4

  $variable: first global value;
   
  .content {
   $variable: second global value !global;
   value: $variable;
  }
   
  .sidebar {
   value: $variable;
  }

Variables functions in Sass

  • In SASS the core library provides us with a couple of advanced functions for dealing with variables.
    Example :
    @use "sass:map";
    
    $theme-colors: (
    
    "success": #28a745,
    
    "warning": #ffc107,
    
    );
    
    .alert {
    
    // Instead of $theme-color-#{warning}
    
    background-color: map.get($theme-colors, "warning");
    
    }

And now after a deep :face_exhaling: dive in the variables concept in SASS. It’s time to make a gentle intro :smiling_face_with_three_hearts::nerd_face: to mixins another amazing concept in SASS to be continued in our next posts.

Mixins in SASS

  • In Sass, a mixins allows us to define styles that can be reused in the entire :astonished: stylesheet. It allows developers to avoid the usage of non semantic classes like .float–right or .float-left.

  • To define a mixins, we use the @mixin at-rule followed by the name, where this name can be any sass identifier. :sunglasses:

  • To include a mixins inside a context, we use the @include keyword followed by the name of the rule. :wink:
    Example :

    @mixin horizontal-list {
     
       li {
         display: inline-block;
         margin: {
           left: -4px;
           right: 3em;
         }
       }
     }
      nav ul {
       @include horizontal-list;
     }

Now we reached the post end. In tomorrow’s post we will dive more into mixins and then we will introduce the functions concept, to utilize more the power of this amazing technology. :zzz::smiling_face_with_three_hearts:

5 Likes

100daysofcode - Day16

Hello friends :star_struck:, a new day is here and some new information is required to wrap up this day successfully :partying_face:.

In yesterday’s post, we talked about some amazing :rocket: concepts in SASS, starting with a deep dive :goggles: into the variable concept, how we use variables and all the related information about them. Then we moved on to a new interesting topic, the mixins where we made a gentle intro about it.

In today’s post :face_with_peeking_eye:, we will continue our tour to learn more about mixins :nerd_face:, and how to use them to write some reusable pieces of code :jigsaw:.

First of all let’s review quickly what mixins are in SASS ? :face_with_monocle:

  • In SASS mixin names are like any other identifier, where any hyphen or underscore are treated the same. In simple terms if we define a mixin called bullets_list and another one named bullets-list. Both of them are treated the same.

Arguments in mixins ? :thinking:

  • A Sass mixin can take arguments which allow the developer to change the behavior of the defined mixin each time it gets called. Any argument can be added after the mixin name, as a list of variables surrounded by parentheses.
    Example :

    @mixin rtl($property, $ltr-value, $rtl-value) {
     #{$property}: $ltr-value;
     
     [dir=rtl] & {
       #{$property}: $rtl-value;
     }
    }
     
    .sidebar {
     @include rtl(float, left, right);
    }
    

Optional arguments in mixins ? :eyes:

  • Every argument declared in a mixin must be passed when this mixin is included. But there is a way to make this argument an optional one by giving it a default value which will be used if the targeted argument isn’t passed.
    Example :

    @mixin replace-text($image, $x: 50%, $y: 50%) {
      text-indent: -99999em;
      overflow: hidden;
      text-align: left;
    
      background: {
        image: $image;
        repeat: no-repeat;
        position: $x $y;
      }
    }
    
    .mail-icon {
      @include replace-text(url("/images/mail.svg"), 0);
    }
    

Arbitrary arguments in Sass mixins

  • A very powerful option, can extend the functionality of a mixin in Sass, if we can pass any number of arguments to it.

  • Can this happen ? :open_mouth: : yeah, in a sass mixin if the last variable end with 3 dots …, then all extra arguments to that mixin are passed to that argument as a list, and this argument is called the argument list.
    Example :

    @mixin order($height, $selectors...) {
      @for $i from 0 to length($selectors) {
        #{nth($selectors, $i + 1)} {
          position: absolute;
          height: $height;
          margin-top: $i * $height;
        }
      }
    }
    
    @include order(150px, "input.name", "input.address", "input.zip");
    

And now after exploring the different ways to deal with a mixin in Sass. It’s time to wrap up our post, stay tuned for tomorrow’s :smiling_face: post which will talk about a new interesting topic in Sass which is the functions :exploding_head: .

7 Likes

100daysofcode - Day17

Hello friends :smiling_face: , the 17/100 day is already here, and a lot of new information are required to crash this amazing day and wrap it successfully :partying_face: .

In yesterday’s post, we discovered the mixins :exploding_head: concepts, which allow developers to write reusable pieces of code, to be used anywhere in the stylesheets.

In today’s post, we will explore together the functions :star_struck: concepts, which add more power to our CSS stylesheet.

Let’s start by defining a function in SASS ? :thinking:

  • A Sass function can simply define complex operations on SassScript values to be re-used throughout the stylesheet.

  • Functions are defined using the @functions at-rule, in the following way @function followed by its name and finally the list of arguments.

  • In Sass functions the @return at-rule indicates the value to use as the result of the function call.
    Example :

    @function pow($base, $exponent) {
      $result: 1;
      @for $_ from 1 through $exponent {
        $result: $result * $base;
      }
      @return $result;
    }
    
    .sidebar {
      float: left;
      margin-left: pow(4, 3) * 1px;
    }
    

How does Sass treat hyphens and underscores while defining a new function ? :thinking:

  • As any other identifier in Sass, when defining a new function in SASS. The hyphens and underscores are treated in the same way. For example if we define a function called compute-pow, and another one called compute_pow. Both of them are treated as an identical one.

Functions with arguments in Sass ? :face_with_peeking_eye:

  • A function in sass can take a list of arguments, taking into consideration that any defined argument must be passed when calling the function.

  • If we need to pass an optional argument to the function, we must add a default value to the targeted argument, so it gets used if no data are passed.
    Example :

    @function invert($color, $amount: 100%) {
      $inverse: change-color($color, $hue: hue($color) + 180);
      @return mix($inverse, $color, $amount);
    }
    
    $primary-color: #036;
    .header {
      background-color: invert($primary-color, 80%);
    }
    

Arbitrary Arguments in Sass functions :eyes:

  • It’s so important to create a reusable function, where we can pass any number of arguments to it every time we call it, and this can be done simply by passing an arbitrary argument to the function.

  • We can pass an arbitrary list of keywords where we use the meta.keywords() function to extract them.

  • Any argument that ends with the three dots … is called an argument list.
    Example :

    @function sum($numbers...) {
      $sum: 0;
      @each $number in $numbers {
        $sum: $sum + $number;
      }
      @return $sum;
    }
    
    .micro {
      width: sum(50px, 30px, 100px);
    }
    

Return in Sass functions :open_mouth:

  • The @return at-rule indicates the result of the function to be called.

  • The return keyword is only allowed within the function body, where each function must end with a @return

  • When a @return is encountered, it immediately ends the function and returns its result.
    Example :

    @use "sass:string";
    
    @function str-insert($string, $insert, $index) {
      // Avoid making new strings if we don't need to.
      @if string.length($string) == 0 {
        @return $insert;
      }
    
      $before: string.slice($string, 0, $index);
      $after: string.slice($string, $index);
      @return $before + $insert + $after;
    }
    
    

calc function in Sass :abacus:

  • The calc() function is a function that takes a single expression as its parameter and takes the expression’s value as the result. The expression can be any simple expression including the basic arithmetic operators like addition, subtraction, multiplication and division.

    #div1 {
      width: calc(100% - 100px);
      heigh: calc(100% / 3);
      padding: 5px;
      text-align: center;
    }
    
6 Likes