search
HomeWeb Front-endCSS TutorialHow do CSS variables work? How to use inline CSS variables for layout?

This 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!

How do CSS variables work? How to use inline CSS variables for layout?

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:

How do CSS variables work? How to use inline CSS variables for layout?

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

How do CSS variables work? How to use inline CSS variables for layout?

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.

How do CSS variables work? How to use inline CSS variables for layout?

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 id="Article-title">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);
}

有了它,我可以调整内联样式以将值更改为另一个关键字。 我发现这在进行快速原型制作甚至是制作网站时很有用。

按钮

按钮宽度

CSS 变量也适用于按钮元素。 假设有一个带有两个input字段和一个按钮的表单。

How do CSS variables work? How to use inline CSS variables for layout?

我的目的是通过使用内联CSS变量来控制按钮的宽度。 有时,按钮应占据其父控件的100%宽度。

html

<button>Submit</button>

css

.c-button {
    /* Other styles */
    width: var(--width, initial);
}

How do CSS variables work? How to use inline CSS variables for layout?

按钮颜色

另一个有用的用途是当有重影按钮(轮廓按钮)时。 按钮的颜色可以是任何颜色,通过使用CSS变量,可以轻松更改颜色。

HTML

<button>Save Edits</button>
<button>Delete</button>

CSS

.c-button--ghost {
  /* Other styles */
  background: transparent;
  color: var(--color, #000);
  border-color: currentColor;
}

How do CSS variables work? How to use inline CSS variables for layout?

CSS 变量同样适合悬停效果。悬停时,按钮背景将变为纯色,并且字体颜色为白色。

How do CSS variables work? How to use inline CSS variables for layout?

事例源码:https://codepen.io/shadeed/pen/NWWXqqX/f8e6969d5145d4dcd81aacf7a037c995

用户头像

每个角色的大小都不同,这非常适合用 CSS 变量来解决。假设有四个不同大小的用户头像。

How do CSS variables work? How to use inline CSS variables for layout?

在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()函数,我可以传递一个--size 变量,它将乘以一个基本宽度值,在HTML中定义 --size变量:

<img  class="c-avatar lazy" src="/static/imghwm/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/imghwm/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/imghwm/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/imghwm/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!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
利用CSS怎么创建渐变色边框?5种方法分享利用CSS怎么创建渐变色边框?5种方法分享Oct 13, 2021 am 10:19 AM

利用CSS怎么创建渐变色边框?下面本篇文章给大家分享CSS实现渐变色边框的5种方法,希望对大家有所帮助!

css ul标签怎么去掉圆点css ul标签怎么去掉圆点Apr 25, 2022 pm 05:55 PM

在css中,可用list-style-type属性来去掉ul的圆点标记,语法为“ul{list-style-type:none}”;list-style-type属性可设置列表项标记的类型,当值为“none”可不定义标记,也可去除已有标记。

css与xml的区别是什么css与xml的区别是什么Apr 24, 2022 am 11:21 AM

区别是:css是层叠样式表单,是将样式信息与网页内容分离的一种标记语言,主要用来设计网页的样式,还可以对网页各元素进行格式化;xml是可扩展标记语言,是一种数据存储语言,用于使用简单的标记描述数据,将文档分成许多部件并对这些部件加以标识。

css3怎么实现鼠标隐藏效果css3怎么实现鼠标隐藏效果Apr 27, 2022 pm 05:20 PM

在css中,可以利用cursor属性实现鼠标隐藏效果,该属性用于定义鼠标指针放在一个元素边界范围内时所用的光标形状,当属性值设置为none时,就可以实现鼠标隐藏效果,语法为“元素{cursor:none}”。

rtl在css是什么意思rtl在css是什么意思Apr 24, 2022 am 11:07 AM

在css中,rtl是“right-to-left”的缩写,是从右往左的意思,指的是内联内容从右往左依次排布,是direction属性的一个属性值;该属性规定了文本的方向和书写方向,语法为“元素{direction:rtl}”。

css怎么设置i不是斜体css怎么设置i不是斜体Apr 20, 2022 am 10:36 AM

在css中,可以利用“font-style”属性设置i元素不是斜体样式,该属性用于指定文本的字体样式,当属性值设置为“normal”时,会显示元素的标准字体样式,语法为“i元素{font-style:normal}”。

css怎么实现英文小写转为大写css怎么实现英文小写转为大写Apr 25, 2022 pm 06:35 PM

转换方法:1、给英文元素添加“text-transform: uppercase;”样式,可将所有的英文字母都变成大写;2、给英文元素添加“text-transform:capitalize;”样式,可将英文文本中每个单词的首字母变为大写。

怎么设置rotate在css3的旋转中心点怎么设置rotate在css3的旋转中心点Apr 24, 2022 am 10:50 AM

在css3中,可以用“transform-origin”属性设置rotate的旋转中心点,该属性可更改转换元素的位置,第一个参数设置x轴的旋转位置,第二个参数设置y轴旋转位置,语法为“transform-origin:x轴位置 y轴位置”。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.