


How do CSS variables work? How to use inline CSS variables for layout?
Jun 14, 2022 am 10:46 AMThis article will take you to understand CSS variables, talk about how CSS variables work, and introduce how to use inline CSS variables to improve the efficiency of smart layout. I hope it will be helpful to everyone!
There are situations where I need a simple way to create a grid layout. For example, quickly draw a five-column grid without modifying the CSS every time I change my mind. In this article, we explore some use cases and think about how to implement and use them. [Recommended learning: css video tutorial]
How it works
Before exploring these concepts in depth, let’s first review the basic knowledge of CSS variables. It can also be called a "custom property".
All major browsers support CSS variables. The following is the support of each browser:
If you want to define CSS variables is a global variable, you need to add it to the :root
declaration (:root
is equivalent to ). If the variable is specific to a component, it can be defined in a declaration within the group.
In the example below, I define a global variable --size
, which is used for the width and height of the square
element.
:root?{ ????--size:?50px; } .square?{ ????width:?var(--size); ????height:?var(--size); }
What should we do if --size
is not defined? CSS supports defining default variables or fallback variables when the passed variables are invalid.
var(--size, 10px)
in the example below. If --size
is invalid, the width and height values ??will be 10px
.
.square?{ ????width:?var(--size,?10px); ????height:?var(--size,?10px); }
In addition to this, you can also use CSS variables in inline CSS styles. For example
HTML
<div></div>
CSS
.elem?{ ????background:?var(--background); }
Next, we use the above concepts and demonstrate some examples.
Everyone said that there is no project to write on the resume, so I found a project for you, and also included a [construction tutorial].
CSS Grid Example
Sidebar and Main Content
In this design , I'm using CSS grid for the following:
Sidebar and main menu
Form items
Three-column layout
#The width of the sidebar is fixed, and the main content changes. Let's say the width of the sidebar is 240px
.
1. Sidebar and main menu
Html
<div> ????<aside></aside> ????<main></main> </div>
Html
.o-grid?{ ????display:?grid; ????grid-template-columns:?var(--columns); }
2. Form items
According to the design, each row has two columns, and the html structure is as follows:
Html
??<div></div> ??<div></div> ??<div></div> ??<div></div>
CSS
.o-grid?{ ????display:?grid; ????grid-template-columns:?var(--columns); }
3. Three column layout
In the example below, I added --repeat-number: 3
and --gap: 8px
as inline CSS. These variables will be added to the o-grid
class and the settings of the grid will be based on these variables.
HTML
??<div></div> ??<div></div> ??<div></div>
CSS
.o-grid?{ ??display:?grid; ??grid-template-columns:?repeat(var(--repeat-number),?1fr); ??grid-gap:?var(--gap,?0); }
I like to add default values ??to CSS variables in case the variable is not set . In the above code, I used var(--gap, 0)
, if the user does not provide the --gap
variable, its default value will be 0
.
Dynamic Grid Items: minmax
For me this is a widely used use case and very important. I use Grid minmax
a lot, but when I use it on multiple pages, I run into a problem.
Let’s take a basic example without using CSS variables.
In CSS I use minmax
to define the minimum width for each grid item 250px
.
CSS
.o-grid?{ ??display:?grid; ??grid-template-columns:?repeat(auto-fit,?minmax(250px,?1fr); ??grid-gap:?16px; }
Now, what should you do if your design requires grid items to be at least 300px
wide? Do I need to create a version like the following?
.o-grid--2?{ ????grid-template-columns:?repeat(auto-fit,?minmax(350px,?1fr)); }
Imagine having five different grids, each with different item widths, so the above is not the correct solution.
Using CSS variables, I can perform the following operations
.o-grid?{ ????display:?grid; ????grid-template-columns:?repeat(auto-fit,?minmax(var(--item-width),?1fr); ????grid-gap:?var(--gap); }
In HTML, I can set CSS variables on tags:
?????<div></div> ?????<div></div> ?????<div></div>?????<div></div> ?????<div></div> ?????<div></div>?????<div></div> ?????<div></div> ?????<div></div>
Example source code: https: //codepen.io/shadeed/pen/xxxPYog/7d3e0d575a5cecb86233fc7d72fa90d4
Flexbox Example
In the example, there is an article title that contains the author name and tags. These layout methods on the page change dynamically, so a method to quickly switch these layout methods is needed.
HTML
<div> ????<h2>Article?title</h2> ????<div> ????????<p>By?Ahmad?Shadeed</p> ????????<p>Published?under:?CSS,?Design</p> ????</div> </div>
CSS
.article-header__meta?{ ????display:?flex; ????justify-content:?var(--justify); }
有了它,我可以調整內聯(lián)樣式以將值更改為另一個關鍵字。 我發(fā)現(xiàn)這在進行快速原型制作甚至是制作網(wǎng)站時很有用。
按鈕
按鈕寬度
CSS 變量也適用于按鈕元素。 假設有一個帶有兩個input
字段和一個按鈕的表單。
我的目的是通過使用內聯(lián)CSS變量來控制按鈕的寬度。 有時,按鈕應占據(jù)其父控件的100%
寬度。
html
<button>Submit</button>
css
.c-button?{ ????/*?Other?styles?*/ ????width:?var(--width,?initial); }
按鈕顏色
另一個有用的用途是當有重影按鈕(輪廓按鈕)時。 按鈕的顏色可以是任何顏色,通過使用CSS變量,可以輕松更改顏色。
HTML
<button>Save?Edits</button> <button>Delete</button>
CSS
.c-button--ghost?{ ??/*?Other?styles?*/ ??background:?transparent; ??color:?var(--color,?#000); ??border-color:?currentColor; }
CSS 變量同樣適合懸停效果。懸停時,按鈕背景將變?yōu)榧兩?,并且字體顏色為白色。
事例源碼:https://codepen.io/shadeed/pen/NWWXqqX/f8e6969d5145d4dcd81aacf7a037c995
用戶頭像
每個角色的大小都不同,這非常適合用 CSS 變量來解決。假設有四個不同大小的用戶頭像。
在CSS中,定義了以下樣式:
.c-avatar?{ ??display:?inline-block; ??margin-right:?2rem; ??width:?calc(var(--size,?1)?*?30px); ??height:?calc(var(--size,?1)?*?30px); ??object-fit:?cover; ??border-radius:?50%; ??box-shadow:?0?3px?10px?0?rgba(#000,?0.2); }
通過使用Calc()
函數(shù),我可以傳遞一個--size
變量,它將乘以一個基本寬度值,在HTML中定義 --size
變量:
<img class="c-avatar lazy" src="/static/imghw/default1.png" data-src="user.jpg" alt="How do CSS variables work? How to use inline CSS variables for layout?" > <img class="c-avatar lazy" src="/static/imghw/default1.png" data-src="user.jpg" alt="How do CSS variables work? How to use inline CSS variables for layout?" > <img class="c-avatar lazy" src="/static/imghw/default1.png" data-src="user.jpg" alt="How do CSS variables work? How to use inline CSS variables for layout?" > <img class="c-avatar lazy" src="/static/imghw/default1.png" data-src="user.jpg" alt="How do CSS variables work? How to use inline CSS variables for layout?" >
事例源碼:https://codepen.io/shadeed/pen/WNNdErw/cdaac5ff667e1f7d9c8241655441f10d
作者:Ahmad shaded
原文:https://css-tricks.com/patterns-for-practical-css-custom-properties-use/
(學習視頻分享:web前端)
The above is the detailed content of How do CSS variables work? How to use inline CSS variables for layout?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The core method of building social sharing functions in PHP is to dynamically generate sharing links that meet the requirements of each platform. 1. First get the current page or specified URL and article information; 2. Use urlencode to encode the parameters; 3. Splice and generate sharing links according to the protocols of each platform; 4. Display links on the front end for users to click and share; 5. Dynamically generate OG tags on the page to optimize sharing content display; 6. Be sure to escape user input to prevent XSS attacks. This method does not require complex authentication, has low maintenance costs, and is suitable for most content sharing needs.

1. Maximizing the commercial value of the comment system requires combining native advertising precise delivery, user paid value-added services (such as uploading pictures, top-up comments), influence incentive mechanism based on comment quality, and compliance anonymous data insight monetization; 2. The audit strategy should adopt a combination of pre-audit dynamic keyword filtering and user reporting mechanisms, supplemented by comment quality rating to achieve content hierarchical exposure; 3. Anti-brushing requires the construction of multi-layer defense: reCAPTCHAv3 sensorless verification, Honeypot honeypot field recognition robot, IP and timestamp frequency limit prevents watering, and content pattern recognition marks suspicious comments, and continuously iterate to deal with attacks.

The core role of Homebrew in the construction of Mac environment is to simplify software installation and management. 1. Homebrew automatically handles dependencies and encapsulates complex compilation and installation processes into simple commands; 2. Provides a unified software package ecosystem to ensure the standardization of software installation location and configuration; 3. Integrates service management functions, and can easily start and stop services through brewservices; 4. Convenient software upgrade and maintenance, and improves system security and functionality.

Different browsers have differences in CSS parsing, resulting in inconsistent display effects, mainly including the default style difference, box model calculation method, Flexbox and Grid layout support level, and inconsistent behavior of certain CSS attributes. 1. The default style processing is inconsistent. The solution is to use CSSReset or Normalize.css to unify the initial style; 2. The box model calculation method of the old version of IE is different. It is recommended to use box-sizing:border-box in a unified manner; 3. Flexbox and Grid perform differently in edge cases or in old versions. More tests and use Autoprefixer; 4. Some CSS attribute behaviors are inconsistent. CanIuse must be consulted and downgraded.

InstallDartSassvianpmafterinstallingNode.jsusingnpminstall-gsass.2.CompileSCSStoCSSusingthecommandsassinput.scssoutput.css.3.Usesass--watchinput.scssoutput.csstoauto-compileonsave.4.Watchentirefolderswithsass--watchscss:css.5.Usepartialswith_prefixfo

accent-color is an attribute used in CSS to customize the highlight colors of form elements such as checkboxes, radio buttons and sliders; 1. It directly changes the default color of the selected state of the form control, such as changing the blue check mark of the checkbox to red; 2. Supported elements include input boxes of type="checkbox", type="radio" and type="range"; 3. Using accent-color can avoid complex custom styles and extra DOM structures, and maintain native accessibility; 4. It is generally supported by modern browsers, and old browsers need to be downgraded; 5. Set accent-col

Thevertical-alignpropertyinCSSalignsinlineortable-cellelementsvertically.1.Itadjustselementslikeimagesorforminputswithintextlinesusingvalueslikebaseline,middle,super,andsub.2.Intablecells,itcontrolscontentalignmentwithtop,middle,orbottomvalues,oftenu

To change the text color in CSS, you need to use the color attribute; 1. Use the color attribute to set the text foreground color, supporting color names (such as red), hexadecimal codes (such as #ff0000), RGB values (such as rgb(255,0,0)), HSL values (such as hsl(0,100%,50%)), and RGBA or HSLA with transparency (such as rgba(255,0,0,0.5)); 2. You can apply colors to any element containing text, such as h1 to h6 titles, paragraph p, link a (note the color settings of different states of a:link, a:visited, a:hover, a:active), buttons, div, span, etc.; 3. Most
