laitimes

Talk about the past and future of CSS and deepen your understanding of CSS

author:Front-end talents
Reprint instructions: The original is not easy, unauthorized reproduction in any form
Talk about the past and future of CSS and deepen your understanding of CSS

A long time ago, CSS was like a breath of fresh air, just simple and easy to add styles to a page.

It involves setting rules for the browser to handle automatically. You can change the margins, font, and size, but that's just scratching the surface, you know?

The real highlight is that "cascade" feature, which allows styles to inherit and override other styles, creating some dynamic, cool pages. Fast forward to today, and CSS is like a Swiss army knife for web design. It has the ability to use flexboxes and grids to animate, transform, and adapt to layouts, making web pages responsive and cool.

From basic styles to complex animations, CSS has evolved to a whole new level. It's no longer just simple styling, but brings your entire web page to life.

Let's dive into how CSS has evolved to this day (or scroll straight to the last section and look to the future...). )。

CSS selectors – the way styles are constantly evolving

CSS selectors are like precise instructions in a tag game. It is a rule for identifying HTML elements that need to be styled. Whether you're pointing to one, <div>.class, or #id, selectors are messengers of your style declaration, ensuring that the correct elements are "tagged". Let me take you back to the early days of CSS. It was a time when web design was fresh, original, and in many ways limited. Remember old HTML tags like font and center? We use them because we have to, not because we want to. Then, like superheroes in comic books in the '90s, CSS came along and it brought the power of selectors. The initial CSS selectors are as basic as the HTML they apply to:

h1 {
  color: blue;
}           

The selector back then was simple and effective, but very limited. It's like drawing the Sistine Chapel with a crayon.

To add more flexibility, CSS2 introduces new selectors such as child element selectors (>), neighbor selectors (+), and attribute selectors ([attr=value]). These selectors allow for more precise styling:

/* Child Selector */
div > p {
  color: red;
}

/* Adjacent Sibling Selector */
h1 + p {
  margin-top: 20px;
}

/* Attribute Selector */
input[type="text"] {
  width: 200px;
}           

These selectors allow us to express more complex relationships between elements, making our style sheets more efficient and organized. This is an improvement, but we still need more.

Then came CSS3. It extends the capabilities of CSS selectors with more powerful tools, such as generic sibling combiners (~), :not() pseudo-classes, and a range of property selectors:

/* General Sibling Combinator */
h1 ~ p {
  font-size: 1.2em;
}

/* :not() Pseudo-class */
div:not(.highlighted) {
  opacity: 0.5;
}

/* Attribute Selectors */
a[href*="google"] {
  background: url(/images/google-icon.png) no-repeat;
}
           

We no longer just style elements, but interact with them, explore their properties, the relationships between them. We started creating complex designs that were responsive to the structure and meaning of the content.

Talk about the past and future of CSS and deepen your understanding of CSS

CSS3 introduces pseudo-classes such as nth-child, :nth-of-type, :checked, and pseudo-elements :before and ::after. Our crayons have become a full palette of artists, and the canvas of the web has become more colorful as a result.

/* :nth-child Selector */
li:nth-child(odd) {
  background: lightgray;
}

/* :checked Pseudo-class */
input[type="checkbox"]:checked {
  border-color: green;
}

/* ::before and ::after Pseudo-elements */
blockquote::before {
  content: "❝";
  font-size: 3em;
}
blockquote::after {
  content: "❞";
  font-size: 3em;
}
           

Also worth mentioning is the pseudo-class: is. It allows you to combine multiple selectors in a single statement, reducing code repetition and improving readability. If you want to dig deeper, check out Steve's article "Simpler CSS Selectors With :is()".

One last mentioned selector is :where, which is similar to :is. However, the key difference is that the specificity of where is always 0.

Selectors give us the tools to express our creative vision in code. They are constantly evolving, pushing the Web into the more exciting frontiers of design.

Cascade – utilizes specificity and inheritance

Cascading is a key feature of CSS that, when used correctly, can make your stylesheets more efficient and easier to maintain. It refers to combining different style sheets and resolving conflicts between different CSS rules that apply to the same element.

The concept of specificity here plays a key role. ID selectors are more specific than class selectors, and class selectors are more specific than type selectors.

#header {
  color: blue; /* This will apply because ID selectors have the highest specificity */
}

.container .header {
  color: red; /* This won't apply to the element with id "header" */
}

header {
  color: green; /* This won't apply to the element with id "header" */
}           

Knowing how to work with Cascade, and not against it, will be able to avoid many problems. Using tools such as the specificity calculator can be very beneficial.

Flexibility for media queries

Media queries are a key advantage of CSS, which provides built-in responsive design capabilities. Media queries help you apply different styles for different devices or screen widths. This flexibility allows you to customize styling based on different device characteristics and screen sizes.

@media only screen and (max-width: 600px) {
  body {
    background-color: lightblue;
  }
}           

In this example, when the screen width is less than or equal to 600px, the background color of the body will change to light blue. This makes CSS play an important role in creating responsive designs.

Let's review how media queries in CSS keep fresh:

  • 1994: Our main figure, Håkon Wium Lie, comes up with the first idea for media inquiries. This is a big start!
  • 1998: CSS2 debuted, giving us our first media query experience.
  • 2001: CSS3 is released, upgrading media queries with new features.
  • 2012: Media inquiries shine! They became W3C recommended standards.

Now: Media queries are supported in all major browsers and become a key tool in responsive web design.

The power of animations and transitions

With CSS3, animations and transitions have become an essential part of modern web pages, creating a dynamic user experience. You can make CSS properties change over time, control the speed of transitions, and create keyframe-based animations.

button {
  transition: background-color 0.5s ease;
}

button:hover {
  background-color: blue;
}           

In this code, when you hover over a button, its background color transitions to blue in half a second.

Embrace the magic of CSS variables (custom properties)

Since its inception in 1997, the CSS Working Group has recognized the need for CSS variables. By the end of the 2000s, developers had created various solutions, such as custom PHP scripts and preprocessors such as Less and Sass, to compensate for this shortcoming.

Realizing that a built-in solution would simplify the process, the group released the first draft of the CSS variable module in 2012. In 2017, it was renamed CSS Custom Properties for Cascading Variables and gained widespread browser support.

In the past, updating CSS values was a manual, time-consuming endeavor, and the era of static CSS is over. Now that we have CSS variables in our toolkit, specific values can be stored and reused throughout the stylesheet. These variables ensure consistency and make updating a breeze.

Here are some examples of CSS variables:

:root {
  --brand-color: #32a852;
}

body {
  background-color: var(--brand-color);
}

/* On hovering over the body, the brand color changes */
body:hover {
  --brand-color: #a83258;
}
           

Hover over the page and voila! Your website style has completely changed. That's the power of CSS variables!

Layout through the ages

CSS layout has undergone many changes over the years. Developers used to use tables and floats to create layouts, but this approach was difficult to maintain and less suited to responsive design. Later, the introduction of media queries, flexboxes, and grid layouts revolutionized the way developers created layouts, making them more responsive and easy to maintain. Let's dive in.

Move away from table-based layouts and move to CSS

At the beginning of the 21st century, the era of table-based layouts began to fade. Remember those days? This is true when we use table, tr, and td to arrange everything on the page, even the layout. Ah, what a beautiful time those days!

<table>
  <tr>
    <td>Header</td>
  </tr>
  <tr>
    <td>Main Content</td>
    <td>Sidebar</td>
  </tr>
  <tr>
    <td>Footer</td>
  </tr>
</table>           

It was a time when we forced HTML to bend as we wanted it to be used for purposes that weren't intended – layout. But hey, we made it work, right? But let's be real, it's a pain. Code is hard to maintain, accessibility suffers, and responsive design is a distant dream. We need a change, and CSS is that change!

The era of floating layouts and the black technology of Clearfix

Ah, the era of floating layouts. Dear readers, I can almost see the nostalgic smiles and frustrated expressions on your faces. You know, before flexbox came along and made our lives a lot easier, we were stuck in the world of floating layouts.

What started as a simple way to arrange text around pictures (imagine the layout of a newspaper), floats became an unexpected tool for creating entire web page layouts.

.column {
  float: left;
  width: 50%;
}           

In this way, we have a two-column layout. Sounds simple, right? But the problem arises when we try to add more elements below the floating element. Suddenly, our footer is like we're running on its own, clinging next to content higher in the DOM structure. Oh, this mess!

Talk about the past and future of CSS and deepen your understanding of CSS

This is due to a special feature of floating elements. They are partially removed in the normal document flow, which means that the elements that follow them in the markup behave as if floating elements do not exist.

To solve this problem, we had to resort to what we now affectionately (or not-so-affectionately) call "ClearFix." This black technique forces the container to expand to include floating elements by creating a new block-level formatting context.

This is the famous Clearfix black technology, which saves many layouts:

.group:after {
  content: "";
  display: table;
  clear: both;
}           

By adding a pseudo-element :after to the container and setting it to display: table; and clear: both; , we effectively cleared the float. Suddenly, our footers are back where they should be and everything is back to normal.

Although floating has some quirky and unexpected behavior, mastering floating is a must for every web developer to grow. It teaches us the importance of understanding the box model of CSS, the flow of documents, and the fantastic and bizarre ways CSS can exhibit. It was a challenging and sometimes maddening experience, but it was an important milestone on the road to the CSS we know and love today.

New layouts with flexbox and grid

Two of the most important game-changers that have greatly improved web development: flexbox. These two guys completely turned the rules of layout design upside down.

The first is flexbox. The flexbox introduced in CSS3 was a complete revolution in box alignment, orientation, order, and size. No more troubles about floating and positioning, everyone pay attention. FlexBox makes it easy to create flexible, responsive layouts with more control with less code. Here's a simple code example that shows you how to use it:

.container {
  display: flex;
  justify-content: space-between;
}

.item {
  flex: 1;
}           

In this example, we set the container to display: flex; to let its child elements know that they are in the flex context. justify-content: space-between; Keep good spacing between our projects. Then we use flex: 1; The same width is added to the item, filling the space of the entire container. Concise and simple.

Then there's the grid layout, the next big leap. Grid layouts were introduced around 2017, taking CSS layout to a whole new level while letting us define columns and rows. CSS grids allow us to create complex two-dimensional layouts that were previously very difficult. Here's a simple example:

.container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 10px;
}

.item {
  grid-column: span 2;
}           

In this code, .container is our grid container. We use grid-template-columns: repeat(3, 1fr); Define three columns of equal width and use grid-gap: 10px; Set the spacing between them to 10 pixels. Then for our project, we use grid-column: span 2; Make the item span two columns. That's a great feature!

If you study the grid-template-areas property, you can become a true CSS grid expert.

Remember the trouble when centering elements? Whether vertically centered or horizontally centered, a combination of attributes such as margin, position, top, left, and transform can make people dizzy.

.container {
  position: relative;
}

.element {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}           

Fast forward to today, and flexbox makes centering a breeze:

.container {
  display: flex;
  justify-content: center;
  align-items: center;
}           

In the past, creating complex layouts often meant using floating elements, which could be tricky and difficult to manage. Here's a simplified example of creating a two-column layout using floating elements:

.container::after {
  content: "";
  display: table;
  clear: both;
}

.column {
  float: left;
  width: 50%;
}           

Today, with CSS Grid, you can create complex layouts with minimal code without headaches:

.container {
  display: grid;
  grid-template-columns: 1fr 1fr;
}           

A glimpse into the future

There are several upcoming features and improvements in CSS that have already attracted a lot of attention in the web design and development community. You can find a detailed list in the Chrome team's latest article, What's New in CSS and UI.

Here are some reasons why I'm excited about some of these features:

Container queries

It is not currently supported in Firefox and Safari

Container queries enable styling of child elements and layout control in layouts. Elements can be changed according to their available space, as follows:

Because of container queries, styles are dynamic. Changing the size of the viewport triggers a change based on the available space for each element.

The syntax is somewhat similar to media queries, except that you only need to define the style you want when the container size meets the criteria:

Here's what the application looks like in practice:

/* Create a containment context */
.post {
  container-type: inline-size; /* size & normal are valid values as well */
}

/* Default heading styles for the card title */
.card h2 {
  font-size: 1em;
}

/* If the container is larger than 700px */
@container (min-width: 700px) {
  .card h2 {
    font-size: 2em;
  }
}           

Style queries

It is not currently supported in Firefox and Safari

Query the style value of the parent container:

<li class="card-container" style="--sunny: true;">
  <div class="weather-card">
    <div class="day">Saturday</div>
    <div class="date">February <span>12</span></div>
    <div class="temps">
      <div class="high">High: <span>55</span></div>/
      <div class="low">Low: <span>47</span></div>
    </div>
    <div class="features">
      Clear skies, sun
    </div>
  </div>
</li>

<style>

.card-container {
  container-name: weather;
}

/* In case the custom propery --sunny: true; change the child */

@container style(--sunny: true) {
 .weather-card {
   background: linear-gradient(-30deg, yellow, orange);
 }

 .weather-card:after {
   content: url(<data-uri-for-demo-brevity>);
   background: gold;
 }
}

</style>           

:has pseudo-class

It is not currently supported in Firefox.

A way to style based on descendant elements. Basically, you can apply styles based on child elements, which means it can serve as an ideal parent selector. However, you can also style child elements inside the parent element.

<article>
 <h1>Hello</h1>
 <h2>World</h2>
</article>

<style>
/* style parent according to children */
article:has(h1) {
 background: lightgray;
}

/* style child by parent content */
article:has(h1) h2 {
   color: yellow;
}

/* style sibling by adjacent element */
h1:has(+ h2) {
 color: hotpink;
}
</style>            

text-wrap: balance

Currently only supported in Chromium

This new value, as the name suggests, will allow you to balance the text so you no longer need to use JS to implement it. Applying it to a block of text will really make your designer happy.

Talk about the past and future of CSS and deepen your understanding of CSS

Nested

It is not currently supported in Firefox

Finally, just like SASS and Less, nesting and co-locating selector-related styles:

.parent {
  color: blue;

  .child {
    color: red;
  }
}           

You can also nest media queries (and container queries):

.card {
  display: flex;
  gap: 1rem;

  @media (width >= 480px) {
    display: grid;
  }
}           

Also, the first example can also be written like this:

.parent {
  color: blue;

  & .child {
    color: red;
  }
}           

Subgrid

Supported in Firefox and Safari, and used under the Chrome logo

Subgrids are part of refining a grid layout that allows you to apply a grid layout to the child elements of grid items, resulting in a more consistent and maintainable layout. Use by adding the grid-template-rows or grid-template-columns property and setting it to the subgrid value:

<div class="grid">
  <div class="item">
    <div class="subitem"></div>
  </div>
</div>

<style>
/* some styles removed for brevity */
.grid {
  display: grid;
  grid-template-columns: repeat(9, 1fr);
  grid-template-rows: repeat(4, minmax(100px, auto));
}

.item {
  display: grid;
  grid-column: 2 / 7;
  grid-row: 2 / 4;
  grid-template-columns: subgrid;
  grid-template-rows: subgrid;
  background-color: #ffd8a8;
}

.subitem {
  grid-column: 3 / 6;
  grid-row: 1 / 3;
  background-color: rgb(40, 240, 83); /* green */
}
</style>           
Talk about the past and future of CSS and deepen your understanding of CSS

Scoped CSS

Still in the working draft stage, specifying the scope for which a particular style applies, essentially creating a native namespace for CSS:

@scope (.card) {
  /* only affects a .title that is within a .card */
  .title { 
    font-weight: bold;
  }
}           

Scrolling driven animations

Still experimental

Controls the playback of the animation based on the scroll position of the scroll container. Once again, the complexity of using JavaScript to create features like parallax scrolling, reading indicators, etc. is reduced. You can see some great demos here.

Talk about the past and future of CSS and deepen your understanding of CSS

Cascading layers (@layer)

It is now widely supported, and the order of precedence is defined in cases where there are multiple cascading layers. You can sort style sheets based on importance:

@layer base {
  a {
    font-weight: 800;
    color: red; /* ignored */
  }

  .link {
    color: blue; /* ignored */
  }
}

@layer typography {
  a {
    color: green; /* styles *all* links */
  }
}

@layer utilities {
  .pink {
    color: hotpink;  /* styles *all* .pink's */
  }
}           

View transitions

(Not supported in Firefox and Safari)

Allows you to change the DOM in a single step while creating animated transitions between two states. It is no longer necessary to use a single-page application (SPA) to accomplish this.

This requires some JavaScript:

function spaNavigate(data) {
  // Fallback for browsers that don't support this API:
  if (!document.startViewTransition) {
    updateTheDOMSomehow(data);
    return;
  }

  // With a transition:
  document.startViewTransition(() => updateTheDOMSomehow(data));
}           

Then CSS takes over:

@keyframes slide-from-right {
  from { opacity: 0; transform: translateX(75px); }
}

@keyframes slide-to-left {
  to { opacity: 0; transform: translateX(-75px); }
}

::view-transition-old(root) {
  animation: 350ms both slide-to-left ease;
}

::view-transition-new(root) {
  animation: 350ms both slide-from-right ease;
}           

Come to an end

The future of CSS is full of huge potential to simplify complex tasks, boost performance, and enable developers to create immersive experiences.

As CSS evolves, we're likely to see new advanced features emerge that blur the line between CSS and JavaScript, providing native solutions for tasks that currently rely on JavaScript libraries.

In addition, more comprehensive CSS frameworks may emerge that take advantage of these new features.

It is important to stay aware of the latest CSS developments as the importance of CSS in web design and development persists. Following CSS Working Group updates, following industry leaders, and exploring new features in browser previews will help you stay updated.

Embrace the exciting possibilities ahead, keep learning, and actively participate in shaping the networks of the future.

Due to the limited space of the content of the article, today's content will be shared here, at the end of the article, I want to remind you that the creation of the article is not easy, if you like my sharing, please don't forget to like and forward, so that more people in need can see. At the same time, if you want to get more knowledge of front-end technology, welcome to follow me, your support will be the biggest motivation for me to share. I'll keep coming out with more content, so stay tuned.