WEBD 150 – CSS Variables & Combinators
April 4, 2024 1:36 am1. Variables
Variables are used to store values that can be reused throughout a CSS document. The scope of a variable—where it can be accessed—is determined by where it is declared.
Global Scope (:root)
First off, what is :root? The :root pseudo class targets the same thing as the html{} selector. It targets the <html> element but, the :root {} pseudo class has more specificity then html{}. This means that whatever you put on the :root will take precedence over things you put on the html{} selector. The :root {} selector should be used for variables and html {} should be used got base styles (even though they technically could be put on :root {}). This is the industry standard.
A variable stored in the :root selector has global scope. This means it can be accessed anywhere in your CSS. The :root pseudo-class represents the highest-level element in the document (the <html> element).
:root {
--border-grey: 2px solid #888;
--border-blue: 2px solid #9b87eb;
}
To use these variables, you apply the var() function to a property:
.wrapper {
border: var(--border-blue);
}
Local Scope
If you declare a variable inside a specific selector, it is localized to that element and its children.
.classname {
--mainCol: red;
}
/* This works because the div is a child of .classname */
.classname div {
color: var(--mainCol);
}
Ordering the CSS With Variables
Now that we are going to start deploying variables, here is how to order it.
/* CSS Document */
/* imports */
@import url('https://fonts.googleapis.com/css2?family=Bitcount+Grid+Double+Ink:[email protected]&display=swap');
/* variables */
:root {
--main-color: rgb(0, 183, 255);
--accent-color: rgb(0, 102, 255);
--border: 5px solid #222;
}
/* Universal Defaults */
html {
}
body {
}
/* Structure */
header {
}
2. Combinators
Combinators allow us to select elements based on their relationship to other elements. This is useful for interactions, such as changing a child’s appearance when a parent is hovered.
A. Descendant Combinator (Space)
Selects all specified elements that are inside a parent element, regardless of how deep they are nested.
div p { color: blue; }
Result: All <p> tags inside any <div> will be blue.
B. Child Combinator (>)
Selects only the immediate children of a parent. It does not select “grandchildren.”
div > p { font-weight: bold; }
C. Next Sibling Combinator (+)
Selects an element that is directly after another specific element at the same level.
h1 + p { margin-top: 0; }
Result: Only the first <p> immediately following an <h1> is affected.
D. Subsequent Sibling Combinator (~)
Selects all siblings that follow a specific element, even if they aren’t directly next to it.
h1 ~ p { color: grey; }
Result: Every <p> that comes after an <h1> (within the same parent) will be grey.
Categorised in: Lectures, Portfolio, WEBD 150
This post was written by amax
Comments are closed here.