Best Website-BuildersBest Website-Builders
    What's Hot

    DA Has Communications Between Stormy Daniels, Trump Lawyer: CNN

    March 22, 2023

    Two held after mob rushes Sydney LGBT protesters

    March 22, 2023

    Social Security launches investigation into disappearance of zombie drug

    March 22, 2023
    Facebook Twitter Instagram
    Facebook Twitter Instagram
    Best Website-BuildersBest Website-Builders
    • Home
    • CSS

      Social Security launches investigation into disappearance of zombie drug

      March 22, 2023

      The Markland area will be closed for about six months

      March 21, 2023

      The battle of ironclads marked the beginning of modern ships

      March 21, 2023

      CDJapan : Pale Moon 32.1.0

      March 21, 2023

      A great SSG just got better

      March 21, 2023
    • Joomla

      Reseller Hosting Business: Important Q&A

      March 21, 2023

      Web Hosting: 8 Elements Every Entrepreneur Should Look For

      March 20, 2023

      VS Code Extension for In-Browser Development, WapuuGotchi Gamification Plugin & More – WP Tavern

      March 20, 2023

      How Superior Web Hosting Support Can Drive Business Success

      March 17, 2023

      PANDACU Studio Website Development Cooperation First Page Sage SEO Dsign Chicago adstargets Cardinal Digital Agency

      March 16, 2023
    • PHP

      Maren Morris introduces son to drag queen and unapologetically shares support for LGBTQ community at Tennessee benefits show

      March 21, 2023

      Gwyneth Paltrow ski crash lawsuit trial begins

      March 21, 2023

      “Anything exciting today?”

      March 21, 2023

      Possible New York Trump indictment attracts demonstrators

      March 21, 2023

      Here are the best cheap wireless earbuds under $25 on Amazon

      March 21, 2023
    • UX

      ‘Laws are working as intended’: Pay transparency brings new awkwardness to the workplace

      March 21, 2023

      Microsoft says PlayStation should make an exclusive to compete with Call of Duty

      March 21, 2023

      How a holistic UX approach adds value to the design process

      March 21, 2023

      Spectrum Access app spotlighted for digital inclusion

      March 21, 2023

      Baidu deploys AI-powered chatbot ‘Ernie Bot’ to improve user experience

      March 21, 2023
    • Web Builders
      1. Web Design
      2. View All

      What Comes First in Website Development — Design or Copy?

      February 2, 2023

      Modern Campus Honors Best Higher Education Websites of 2022

      February 2, 2023

      Premier SEO Consultant in Las Vegas, Nevada with Unparalleled Customer Service

      February 2, 2023

      Can Religious Freedom Be Saved? This group is racing the clock to teach America’s first freedom

      February 2, 2023

      How i Create New Google Account

      February 7, 2023

      CWT powers tools for meeting and event planners

      January 31, 2023

      Best Website Builder – Website Builders

      January 24, 2023

      Is There A Market For Rap-Themed Slot Games? – Rap Review

      January 19, 2023
    • WordPress

      Is Duolingo developing a new music-learning app? We interpret the signs

      March 21, 2023

      The latest news, rumors and everything we know so far | Tech Radar

      March 21, 2023

      The Pro version of the Nvidia RTX 4090 Mobile may be a bit of a disappointment

      March 21, 2023

      Russia orders civil servants to ditch iPhones

      March 21, 2023

      Crypto stealers target .NET developers in new campaign

      March 21, 2023
    • Realtoz
      • Our Other Sites
    • More News
    Best Website-BuildersBest Website-Builders
    Home » How to use CSS variables like a pro
    CSS

    How to use CSS variables like a pro

    websitebuildersnowBy websitebuildersnowFebruary 1, 2023No Comments5 Mins Read
    Facebook Twitter LinkedIn Telegram Pinterest Tumblr Reddit WhatsApp Email
    Share
    Facebook Twitter LinkedIn Pinterest Email


    CSS variables, also known as custom properties, can be used to minimize repetition in style sheets. This saves time and effort when making design changes. Also, you won’t miss a value that needs to be updated.


    Once you access the DOM, you can create variables, store them, and reuse them throughout your stylesheet.


    How CSS variables are defined and used

    To make your style sheets more organized, easier to maintain, and easier to reuse, any property that accepts a value can make use of CSS variables.

    Here’s an example HTML and CSS file that doesn’t use CSS variables.

    HTML:

     <!DOCTYPE html>
    <html lang="en">
      <head>
        <title>CSS Variables - Button Variations</title>
        <link rel="stylesheet" href="Variables.css" />
      </head>
      <body>
        <div>
          <h1>CSS Variables</h1>
          <div>
            <button class="btn sub-primary">Primary</button>
            <button class="btn">Secondary</button>
          </div>
        </div>
      </body>
    </html>

    CSS:

     .btn {
      padding: 1rem 1.5rem;
      background: transparent;
      font-weight: 700;
      color: red;
    }

    The page looks like this:

    Screenshot of two buttons styled red with CSS

    of .btn The classes used in the style sheet above are not dynamic, so you’ll need to create separate classes to customize each individual button. To create a beautiful website, the front-end style should be dynamic. Implementing a button like this makes it cumbersome to accomplish that task.

    As with most programming languages, CSS variables need to be initialized and replaced.

    To initialize a CSS variable, prefix the variable name with two hyphens.

     :root{
    }

    Note that variables can be initialized anywhere, but only within the initialized selector. For this reason, CSS variables are usually initialized inside the root selector. It targets the top-level element of the DOM and allows you to access variables throughout the HTML document on a global scale.

    To replace variables with CSS styles, var() property:

     :root {
      
      --primary:
      --secondary:
    }

    .btn {
      padding: 1rem 1.5rem;
      background: transparent;
      font-weight: 700;
      color: var(--primary);
      background-color: var(--secondary);
    }

    .sub-primary {
      color: var(--secondary);
      background-color: var(--primary);
    }

    A route selector contains two variables. – Major and –secondary. Then both variables are .btn classes as color and background color respectively.

    Variables make it easier to style individual elements. By reusing variables, you can quickly change the value once and have it updated in all instances.

    Screenshot of two buttons styled with different colors using CSS variables

    of var() Properties can also take a second argument. This argument serves as a fallback value for the first argument in situations where the first argument is undefined or invalid.

    for example:

     :root {
      --primary:
      --secondary:
    }

    .btn {
      padding: 1rem 1.5rem;
      background: transparent;
      font-weight: 700;
      color: var(--primary, blue);
    }

    In this example, – Major to a variable colour style. If for some reason this value fails, the stylesheet will use her second value as a fallback. You can also use another CSS variable as a fallback value.

    Manipulating and Overriding CSS Variables with JavaScript

    Using JavaScript to manipulate CSS variables is a powerful way to change the look and feel of your website on the fly. You can use JavaScript to update the values ​​of these variables and see the changes reflected on your site.

    Note that changes made in JavaScript apply only to the current session. To make changes permanent, you need to update the original source or store the new value on the client like a cookie.

    Here’s an example of how to update the value of a CSS variable using JavaScript.

    HTML:

     <!DOCTYPE html>
    <html lang="en">
      <head>
        <title>CSS Variables - Button Variations</title>
        <link rel="stylesheet" href="Variables.css" />
        <script>
        function changeColor() {
          
          const myElement = document.querySelector(":root");

          
          let currentValue = getComputedStyle(myElement).getPropertyValue(
            "--secondary"
          );

          // Set the new value for the variable
          myElement.style.setProperty("--secondary", "#DAF7A6");
        }
        </script>
      </head>
      <body>
        <div>
          <h1>CSS Variables</h1>
          <div>
            <button class="btn sub-primary" onclick="changeColor()">
             Primary
           </button>
            <button class="btn">Secondary</button>
          </div>
        </div>
      </body>
    </html>

    CSS:

     :root {
      --primary:
      --secondary:
    }

    .btn {
      padding: 1rem 1.5rem;
      background: transparent;
      font-weight: 700;
    }

    .sub-primary {
      color: var(--primary);
      background-color: var(--secondary);
    }

    In this JavaScript code, change color () The function updates the color of the first button when the user clicks it.

    You can use DOM traversal methods to access classes or selectors applied to the HTML document and manipulate their values.

    Before clicking the button:

    Screenshot of the two buttons.One of them is styled with a CSS variable

    After clicking the button:

    Screenshot of the two buttons.One of them used JavaScript and CSS variables to style the white

    You can also use JavaScript to create new CSS variables or remove them entirely.

    for example:

     // Create a new variable
    document.documentElement.style.setProperty('--new-color', 'blue');


    document.documentElement.style.removeProperty('--new-color');

    Using CSS variables in preprocessors

    The use of variables within front-end technologies was first achieved with CSS preprocessors such as: SASS, LESS, and Stylus.

    The purpose of CSS preprocessors is to develop code that extends the basic functionality of standard CSS. It then compiles that code into standard CSS for browsers to understand.

    With the development of CSS variables, preprocessors have become less important, but they can still provide some use when combined with CSS variables in your project.

    SASS variables can be defined $ main color Use it to set the value of a CSS variable. Then use the CSS variable in your regular style class.

    You can also use SASS functions to manipulate the values ​​of CSS variables.

    for example:

     :root {
      --primary: $main-color;
      --secondary: lighten(var(--primary), 20%);
    }

    .btn {
      color: var(--primary);
      background-color: var(--secondary);
    }

    where the SASS function Brighten() operate on the value of – Major get the value of –secondary.

    Note that SASS variables are not accessible from JavaScript. Therefore, if you need to manipulate the value of a variable at runtime, you should use CSS variables.

    Using CSS variables and preprocessors together gives you the best of both worlds, including powerful preprocessor features such as loops and functions, and CSS variable features such as CSS cascading.

    Tips for using CSS variables in web development

    Here are some important tips to make better use of CSS variables.

    Start with a clear naming convention

    Choose a naming convention that makes variables easy to understand and use. For example, using prefixes like: – colour- color variable or –interval- for interval variables.

    Using variables in media queries

    Using variables in media queries makes it easy to adjust your design for different screen sizes.

    Take advantage of the cascading nature of CSS

    Note that CSS variables are cascading. In other words, setting a variable on a parent element affects all its children.

    Use CSS variables with care

    Using too many CSS variables can be confusing, so use them sparingly and only when it makes sense and makes your code more maintainable.

    test the variable

    CSS variables are a unique way to write clear, maintainable code within your style sheets.

    Please note that it is not yet fully supported by all browsers. Therefore, you should test your variables for browser compatibility to ensure that they work as expected and fallback values ​​work as expected.



    Source link

    Share this:

    • Tweet
    • Email
    • Pocket
    • Mastodon
    • WhatsApp
    • Telegram
    • Share on Tumblr
    • Print
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Telegram Email
    Previous ArticleAesirX Launches New Headless CMS Experience, Shaping the Future of Privacy by Design
    Next Article House prices fall for fifth month in a row
    websitebuildersnow
    • Website

    Related Posts

    Social Security launches investigation into disappearance of zombie drug

    March 22, 2023

    The Markland area will be closed for about six months

    March 21, 2023

    The battle of ironclads marked the beginning of modern ships

    March 21, 2023
    Add A Comment

    Leave a Reply Cancel reply

    Top Posts

    Subscribe to Updates

    Get the latest sports news from SportsSite about soccer, football and tennis.

    Advertisement
    Demo

    This website provides information about CSS and other things. Keep Supporting Us With the Latest News and we Will Provide the Best Of Our To Makes You Updated All Around The World News. Keep Sporting US.

    Facebook Twitter Instagram Pinterest YouTube
    Top Insights

    DA Has Communications Between Stormy Daniels, Trump Lawyer: CNN

    March 22, 2023

    Two held after mob rushes Sydney LGBT protesters

    March 22, 2023

    Social Security launches investigation into disappearance of zombie drug

    March 22, 2023
    Get Informed

    Subscribe to Updates

    Get the latest creative news from FooBar about art, design and business.

    © 2023 bestwebsite-builders. Designed by bestwebsite-builders.
    • Home
    • About us
    • Contact us
    • DMCA
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.