CSS Variables

CSS Variables

CSS var() method allows you to create variables and set custom style values is such variables. You can then use those variables to style elements with great ease which will also make your task easier when you need to change the entire theme color settings or other styles as changing value is one place will affect all the related elements.

Defining CSS Variables

Variables in CSS must be declared within a selector that defines its scope. For global scope, you can use :root or body as selectors. Variable names must start with two dashes (--).

VAR SYNTAX

var(custom-name, fallback-value)

The var() method must include a variable while the fallback value is optional. The fallback value will be used in case the variable is invalid.

Example

<div class="class1">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
  tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
  quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
  consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
  cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
  proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>

<style>
:root {
  --theme-background: linear-gradient(#066,#d7d7d7); 
  --theme-color: #222;
  --theme-font-size: 16px;
  --theme-margin: 15px;
  --theme-padding: 15px;
}

.class1{
  background: var(--theme-background, #151f28);
  margin: var(--theme-margin);
  padding: var(--theme-padding);
}

p{
  color: var(--theme-color);
  font-size: var(--theme-font-size);
}
</style>

Result

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.



0 Like 0 Dislike 0 Comment Share

Leave a comment