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

2e503ff7cd53f230a1551def3669e4ac.jpeg

1a94a07dc745546da8d7f5904e17b21d.jpeg

Long ago, CSS was like a breath of fresh air for simply and easily styling pages.

It involves setting rules and letting the browser handle it automatically. You can change margins, fonts, and sizes, but that's just scratching the surface, you know?

The real highlight is the "cascading" feature, which allows styles to inherit and override other styles, creating some dynamic, cool pages. Fast forward to today and CSS is like the swiss army knife of web design. It has the ability to use flex boxes and grids to animate, transition and adapt to layouts, making web pages responsive and cool.

From basic styling to complex animations, CSS has evolved to a whole new level. It's no longer just about styling, it's about bringing your entire web page to life.

Let's take a deep dive into how CSS has come to be (or just scroll to the last section and look into the future...).

CSS selectors - the ever-evolving path of styling

CSS selectors are like precise instructions in the tag game. It is a rule that identifies HTML elements that need to be styled. Whether you're pointing to a <div>, .class, or #id, selectors are the messengers of your style declarations, ensuring the correct element is "marked". Let me take you back to the early days of CSS. It was a time when web design was fresh, raw, and in many ways limited. Remember the old HTML tags like font and center? We use them because we have to, not because we want to. Then, like a 90s comic book superhero, CSS came along, bringing with it the power of selectors. Originally CSS selectors were as basic as the HTML they were applied to:

h1 {
  color: blue;
}

Selectors back then were simple, effective, but very limited. It's like drawing the Sistine Chapel with crayons.

In order to add more flexibility, CSS2 introduces new selectors, such as child element selector (>), adjacent sibling selector (+) and attribute selector ([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 stylesheets more efficient and organized. This is progress, but we still need more.

Then came CSS3. It extends the capabilities of CSS selectors with more powerful tools, such as the universal sibling combinator (~), the :not() pseudo-class, and a series of attribute 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're no longer just styling elements, we're interacting with them, exploring their properties, the relationships between them. We set out to create complex designs capable of responsive layout based on the structure and meaning of the content.

4acdc65990a52ad36fb28d3d8cfa92b2.jpeg

CSS3 brings pseudo-classes like :nth-child , :nth-of-type , :checked , and pseudo-elements ::before and ::after . Our crayons have been transformed into a full artist palette, and the Web's canvas has become even more colorful because of it.

/* :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 one statement, reducing code duplication and improving readability. If you want to dig deeper, check out Steve's article "Simpler CSS Selectors With :is()".

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

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

Cascading - Exploiting Specificity and Inheritance

Cascading is a key feature of CSS that, when utilized 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.

Here the concept of specificity plays a key role. ID selectors are more specific than class selectors, which 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 the cascade, rather than against it, will avoid many problems. Using tools such as specificity calculators can be of great benefit.

Flexibility with media queries

Media queries are a key strength 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 styles 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 become light blue. This makes CSS play an important role in creating responsive designs.

Let's review how media queries in CSS are kept fresh:

  • 1994: Our main character Håkon Wium Lie comes up with the first idea for media queries. This is a big start!

  • 1998: CSS2 debuts, bringing us our first experience with media queries.

  • 2001: CSS3 debuts, bringing media queries to the next level with some new features.

  • 2012: Media queries shine! They become W3C recommended standards.

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

Powerful capabilities for animations and transitions

Through CSS3, animations and transitions have become an essential part of the modern web, 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 the button, its background color transitions to blue for 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 fill this gap.

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

In the past, updating CSS values ​​was a manual, time-consuming job, and the days of static CSS are over. We now have CSS variables in our toolkit to store and reuse specific values ​​throughout our stylesheets. These variables ensure consistency and make updates 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 looks completely different. This is the power of CSS variables!

Layout of past dynasties

Over the years, CSS layout has undergone many changes. Developers used to create layouts using tables and floats, but this approach was hard to maintain and not well suited for responsive design. Later, the introduction of media queries, flexbox, and grid layouts revolutionized the way developers create layouts, making them more responsive and easy to maintain. Let's take a deeper look.

Move away from table-based layouts and move to CSS

Well into the early 2000s, the days of table-based layouts began to fade. Remember those times? When we use table, tr and td to arrange everything on the page, even the layout. Ah, those were the 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 to our will, using it for something it wasn't intended to do - layout. But hey, we made it work, right? But let's be real, it was a pain. Code was hard to maintain, accessibility suffered, and responsive design was a distant dream. We need a change, and CSS is that change!

The era of floating layout and the black technology of clearfix

Ah, the age of floating layouts. Dear readers, I can almost see the nostalgic smiles and the looks of frustration on your faces. You guys know we were stuck in the world of floating layouts until flexbox came along and made our lives a lot easier.

What started as an easy way to arrange text around images (think newspaper layouts), floats became an unexpected tool for creating entire web page layouts.

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

And just like that, we have a two-column layout. Sounds easy, right? But the problem comes when we try to add more elements below the floated element. All of a sudden, our footer is like breaking out on its own, clinging next to content higher up in the DOM structure. Oh the mess!

0371c928146bbe8ee34a9e46eb74b3e3.jpeg

This is due to a special property of floated elements. They are partially removed in the normal document flow, which means that elements following them in the markup behave as if the floated element didn't exist.

To fix this, we had to resort to what we now affectionately (or not so affectionately) call "clearfix hacks". This hack works by creating a new block-level formatting context, forcing the container to expand to contain floated elements.

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 display: table; and clear: both; to it, we effectively clear the float. All of a sudden, our footers are back where they should be, and everything is back to normal.

Despite some quirky and unexpected behavior with floats, mastering floats is a growth imperative for every web developer. It taught us the importance of understanding CSS's box model, document flow, and the wonderful and bizarre ways CSS can behave. It was a challenging and sometimes maddening experience, but an important milestone on the road to the CSS we know and love today.

Brand new layout using flexbox and grid

Two of the most important game-changing factors that have greatly improved web development are: flexbox. These two guys completely turned the rules of layout design on its head.

The first is flexbox. The introduction of flexbox in CSS3 is a complete revolution in setting the alignment, direction, order and size of boxes. There is no need to deal with the trouble of floating and positioning anymore, everyone pay attention. flexbox makes it easy to create flexible, responsive layouts with less code and more control. Here is a simple code example to show 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 children know that they are in a flex context. justify-content: space-between; Let's keep the spacing between our items nice. Then we use flex: 1; to add the same width to the item, filling the entire container space. Clean and simple.

Then came the grid layout, the next big leap. Introduced around 2017, the Grid layout took CSS layout to a whole new level while letting us define columns and rows. CSS grid allows us to create complex two-dimensional layouts that were previously very difficult. Here is 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); to define three columns of equal width, and use grid-gap: 10px; to set the gap between them to 10px. Then for our items, we use grid-column: span 2; to make the items span two columns. That's a really powerful feature!

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

Remember the trouble with centering elements? Whether centering vertically or horizontally, the combination of various properties such as margin, position, top, left, and transform is enough to 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 can be tricky and difficult to manage. Here's a simplified example of creating a two-column layout with floated 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 and no headaches:

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

glimpse of the future

There are several upcoming features and improvements in CSS that are already getting 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's why I'm excited about some of these features:

container query

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 the available space of the element, as follows:

e073527fcfe35573fa70085dd4bed39a.gif

Styles are dynamic due to container queries. Resizing the viewport triggers changes based on the available space for each element.

The syntax is somewhat similar to media queries, except that you only need to define the styles needed when the container size meets the condition:

Here's what it looks like in action:

/* 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 query

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

Not currently supported in Firefox.

A method for setting styles based on descendant elements. Basically, you can apply styles based on child elements, which means it works as a kind of ideal parent selector. However, you can also style child elements inside a 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 text, so you no longer need to use JS to do so. Applying this to text blocks will really make your designers happy.

612cc4c44465c9fdac3dc526bb69a893.gif

nesting

Not currently supported in Firefox

Finally, just like SASS and Less, nest and co-locate selector-related styles:

.parent {
  color: blue;

  .child {
    color: red;
  }
}

Additionally, you can nest media queries (and container queries):

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

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

Alternatively, the first example could also be written like this:

.parent {
  color: blue;

  & .child {
    color: red;
  }
}

subgrid

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

Subgrids are part of the refinement of Grid Layout, allowing grid layout to be applied to the child elements of a grid item, resulting in a more consistent and maintainable layout. Use by adding grid-template-rows or grid-template-columns property and setting as 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>

363462843a2cd25b07696695d28b617e.jpeg

Scoped CSS

Still in working draft stage, specifying where a particular style applies, essentially creating a local namespace for CSS:

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

scroll driven animation

still experimental

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

6d14585f7d15721c64ea9a1ee34f4288.gifcascade layer (@layer)

Now widely supported, the order of precedence is defined in the presence of multiple cascaded layers. You can sort stylesheets by 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 changing 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 do 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;
}

Finish

The future of CSS is full of great potential to simplify complex tasks, improve performance, and allow developers to create immersive experiences.

As CSS evolves, we may see new advanced features emerge that blur the lines between CSS and JavaScript, providing native solutions for tasks that currently rely on JavaScript libraries.

Additionally, more comprehensive CSS frameworks may emerge that take advantage of these new capabilities.

It is very important to stay informed on the latest CSS developments as the importance of CSS in web design and development continues. Following updates from the CSS Working Group, 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 web of the future.

Due to the limited space of the article, today’s content will be shared here. At the end of the article, I would like 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 it, so that more people in need can see it. At the same time, if you want to gain more knowledge of front-end technology, welcome to follow me, your support will be the biggest motivation for me to share. I will continue to output more content, so stay tuned.

Guess you like

Origin blog.csdn.net/Ed7zgeE9X/article/details/131798843