惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Vercel News
Vercel News
O
OpenAI News
Engineering at Meta
Engineering at Meta
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
月光博客
月光博客
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
WordPress大学
WordPress大学
宝玉的分享
宝玉的分享
GbyAI
GbyAI
T
The Blog of Author Tim Ferriss
Google DeepMind News
Google DeepMind News
B
Blog RSS Feed
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
云风的 BLOG
云风的 BLOG
罗磊的独立博客
S
SegmentFault 最新的问题
The Register - Security
The Register - Security
Hugging Face - Blog
Hugging Face - Blog
D
DataBreaches.Net
U
Unit 42
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
B
Blog
阮一峰的网络日志
阮一峰的网络日志
P
Proofpoint News Feed
雷峰网
雷峰网
V
Visual Studio Blog
小众软件
小众软件
aimingoo的专栏
aimingoo的专栏
N
Netflix TechBlog - Medium
酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Y
Y Combinator Blog
博客园 - 【当耐特】
G
Google Developers Blog
L
LangChain Blog
Stack Overflow Blog
Stack Overflow Blog
I
InfoQ
Martin Fowler
Martin Fowler
F
Fortinet All Blogs
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
The Cloudflare Blog
AI
AI
Google Online Security Blog
Google Online Security Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
博客园 - Franky
Blog — PlanetScale
Blog — PlanetScale
Webroot Blog
Webroot Blog
PCI Perspectives
PCI Perspectives
爱范儿
爱范儿
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org

Ahmad Shadeed

Better fluid sizing with round() Use Cases for Field Sizing The Basics of Anchor Positioning Item Flow CSS Relative Colors Balancing Text In CSS Should masonry be part of CSS grid? CSS display contents CSS Grid Areas CSS Cap Unit An Interactive Guide to CSS Container Queries CSS :has() Interactive Guide CSS Nesting UX in DevTools CSS Nesting Future CSS: State Container Queries Rebuilding a comment component with modern CSS Conditional CSS with :has and :nth-last-child CSS Text balancing with text-wrap:balance CSS Masking Do we need CSS flex-wrap detection? My CSS Wishlist Conditional CSS CSS Style Queries Inside the mind of a frontend developer: Article layout Inside the mind of a frontend developer: Hero section CSS container queries are finally here The CSS behind Figma First Look At The CSS object-view-box Property Learn CSS Subgrid CSS :has Parent Selector Aligning Content In Different Wrappers Flexbox Dynamic Line Separator Hello, CSS Cascade Layers Building UI Components With SVG and CSS A Deep CSS Dive Into Radial And Conic Gradients Defensive CSS Building Real-life Components: Facebook Messenger Conditional Border Radius In CSS CSS Container Query Units Less Absolute Positioning With Modern CSS Aligning a Button Label Vertically Comparing Design Mockups To Code Result Using HSL Colors In CSS Custom Scrollbars In CSS Let CSS Container Queries For Designers The State of CSS Cross-Browser Development Overflow Issues In CSS Inspect Element As A Way To Increase Your Curiosity Handling Text Over Images in CSS Digging Into CSS Logical Properties Clipping Scrollable Areas On The inline-start Side Understanding Clip Path in CSS The Art of Building Real-life Components Handling Short And Long Content In CSS CSS Scroll Snap A Deep Dive Into CSS Grid minmax() CSS Variables 101 Finding The Root Cause of a CSS Bug Learn CSS centering How to detect browser support for Flexbox Gap CSS Mistakes While On Autopilot Digging Into the Flex Property Aligning Logo Images in CSS Grid for layout, Flexbox for components Colors in CSS Thinking About The In-between Design Cases min(), max(), and clamp() CSS Functions Image Techniques On The Web Everything About Auto in CSS Learn Box Alignment Let Learn CSS Positioning Intrinsic Sizing In CSS CSS Grid Template Areas In Action Hiding Elements On The Web Creating a Variable Color Font From Scratch Building a Football Ticket With CSS and SVG Blending Modes in CSS CSS Variables With Inline Styles Implementing Dark Mode For My Website Rebuilding Apple Music Header in HTML & CSS Accessible Checkbox Layout Flickering On Browser Resize Enhancing The Clickable Area Size Custom Underlines with SVG Part 3: The Process of Implementing A UI Design From Scratch Part 2: The Process of Implementing A UI Design From Scratch Building An Old Nav Design CSS Flexbox: 5 Real World Use Cases I Used CSS Inline Flex For The First Time The Process of Implementing A UI Design From Scratch Common CSS Issues For Front-End Projects Handling Long and Unexpected Content in CSS How to Build Web Form Layouts With CSS Grid Grid Layout Ah-ha Moment Enhancing Our Components with CSS :empty Building Resizeable Components with Relative CSS Units CSS Writing Mode The Journey of Learning Front End Web Development on a Daily Basis
Understanding CSS Multiple Backgrounds
Ahmad Shadeed · 2020-07-22 · via Ahmad Shadeed

The Layout Maestro

I spent years teaching CSS layout on this blog. I put everything I know into The Layout Maestro course: 70+ lessons and 150+ interactive examples that teach you how to think CSS layouts, not just memorize syntax.

Get the course

CSS background is one of the most used CSS properties. However, using multiple backgrounds is still not well known across all developers. I will hugely focus on the potential of using multiple backgrounds and leverage the CSS to its full power.

In this article, I will explain the background-image property in detail, and provide a visual explainer on how we can stack multiple backgrounds, and the actual benefit of it. Of course, there will be some visual examples, you’re in for a treat!

If you don’t know about CSS background property, I prefer to have a look at this reference by Mozilla Developer Network (MDN) that explains about how CSS background works.

Introduction

The CSS background property is a shorthand for the following properties.

background-clip, background-color, background-image, background-origin, background-position, background-repeat, background-size, and background-attachment.

For this article, I will focus on background-image, background-position, and background-size. Are you ready? Let’s dive in!

Consider the following example.

.element {
  background: url(cool.jpg) top left/50px 50px no-repeat;
}

The background image is positioned at the top-left corner of the element, with a size of 50px * 50px. It’s important to understand and remember the order of the position and size.

In the figure above, the background-position is followed by the background-size. It can’t work the other way around! In other words, the following CSS is invalid:

.element {
  /* Warning: Invalid CSS */
  background: url(cool.jpg) 50px 50px / top left no-repeat;
}

Background Position

An element is positioned relative to the positioning layer set by the background-origin property. I like the flexibility of the background-position. It has multiple ways of positioning elements:

  • Keyword values (top, right, bottom, left, center)
  • Percentage values. E.g: 50%
  • Length values. E.g: 20px 2.5rem
  • Edge offset values. E.g: top 20px left 10px

The coordinates system starts from the top-left corner, with the default value of 0% 0%.

It’s worth mentioning that the value top left is the same as left top. The browser is smart enough to determine which one of them is for the x-axis, and which is for the y-axis.

.element {
  background: url(cool.jpg) top left/50px 50px no-repeat;
  /* is the same as */
  background: url(cool.jpg) left top/50px 50px no-repeat;
}

Background Size

The name of the property is self-explanatory. The size consists of width & height. For the background-size property, the first one is width, and the second is height.

It’s not necessary to use two values. You can use one value and it will be used for the width and height.

Disclaimer: it’s worth mentioning that the CSS spec says: “If only one value is given the second is assumed to be auto”. However, that is not implemented in browsers and will change in the future. Thanks to Ilya Streltsyn for the note.

Now that I went through the basics of how a CSS background works, let’s explore how to use multiple backgrounds.

The background property can have one or more layers, separated by a comma. If the size of multiple backgrounds is the same, one of them will cover the other background.

.element {
  background:
    url(cool.jpg) top left/50px 50px no-repeat,
    url(cool.jpg) center/50px 50px no-repeat;
}

In the figure above, we have two background layers. Each one of them is positioned differently. That is a basic usage of multiple backgrounds. Let’s explore a more advanced example.

The Stacking Order

When placing multiple backgrounds, and one of them is taking the full width and height of its parent, the stacking order will take place. It can be a bit confusing to decide when backgrounds should stack above each other. Consider the following example.

.hero {
  min-height: 350px;
  background:
    url("table.jpg") center/cover no-repeat,
    url("konafa.svg") center/50px no-repeat;
}

We have a plate and a table. What would you expect the result of the CSS above? Which will come first? The plate, or the table?

The answer is the table. In CSS, the first background can stack on the second one, and the second can stack on the third, and so on. By replacing the order of the backgrounds, the result will be as expected.

.hero {
  background:
    url("konafa.svg") center/50px no-repeat,
    url("table.jpg") center/cover no-repeat;
}

Solid Colors

Say you want to draw two rectangles with CSS backgrounds, how would you do it? Thankfully, it’s fairly easy with CSS gradients. When a linear-gradient has the same color stops, the result will be a solid color. That’s it!

.hero {
  background: linear-gradient(#3c88ec, #3c88ec);
}

We can take this way further by exploring a very, very useful use-case for CSS gradients, which is drawing in CSS. Stay tuned for the use-cases section!

Use Cases and Examples

Hero Section Overlay

Often times, you might need to place an overlay on top of the hero section, so the text can be easy to read. This can be easily done by stacking two backgrounds.

.hero {
  background:
    linear-gradient(rgba(0, 0, 0, 0.15), rgba(0, 0, 0, 0.15)),
    url("landscape.jpg") center/cover;
}

What’s even better is that we can use the same method above to apply tints to an element. Consider the following:

.hero {
	background: linear-gradient(135deg, rgba(177, 234, 77, 0.25), rgba(69, 149, 34, 0.25),
    url("landscape.jpg") center/cover;
}

Drawing with CSS

The possibilities of using CSS gradients to draw are endless. You can use linear-gradient or radial-gradient and more. For this basic example, I will explain how to draw a laptop.

Let’s disassemble the laptop and see what gradients we need to use.

Notice how when the laptop items are dissembled, it’s easier now to think about how to implement this as multiple CSS backgrounds now. If you noticed, I created two circles to act as the rounded corners for the body since there is no direct way of doing a gradient with rounded edges.

Next is the drawing. The first thing is to define each gradient as a CSS variable, and its size. I like to use CSS variables since it can reduce code complexity and makes the code cleaner and easier to read. Once done, I will move to the step of positioning them.

:root {
  --case: linear-gradient(#222, #222);
  --case-size: 152px 103px;

  --display: linear-gradient(#fff, #fff);
  --display-size: 137px 87px;

  --reflection: linear-gradient(205deg, #fff, rgba(255, 255, 255, 0));
  --reflection-size: 78px 78px;

  --body: linear-gradient(#888, #888);
  --body-size: 182px 9px;

  --circle: radial-gradient(
    9px 9px at 5px 5.5px,
    #888 50%,
    transparent 50%
  );
  --circle-size: 10px 10px;
}

Now that we defined the gradients and their sizes, the next step is to position them. Consider the following figure for a better visual explainer.

Display Reflection

As explained previously, an element that needs to be on the top should be defined first. In our case, the display reflection should be the first gradient.

LCD Display

The display is centered in the x-axis and is positioned 6px from the y-axis.

Plastic Case

The case is positioned below the display, and it’s centered on the x-axis and positioned 0px from the y-axis.

Body

That’s the most interesting component in the drawing. First, the body is a rectangle, and we have two circles for each side (left and right).

Final Result

:root {
  --case: linear-gradient(#222, #222);
  --case-size: 152px 103px;
  --case-pos: center 0;

  --display: linear-gradient(#fff, #fff);
  --display-size: 137px 87px;
  --display-pos: center 6px;

  --reflection: linear-gradient(205deg, #fff, rgba(255, 255, 255, 0));
  --reflection-size: 78px 78px;
  --reflection-pos: top right;

  --body: linear-gradient(#888, #888);
  --body-size: 182px 9px;
  --body-pos: center bottom;

  --circle: radial-gradient(
    9px 9px at 5px 5.5px,
    #888 50%,
    transparent 50%
  );
  --circle-size: 10px 10px;
  --circle-left-pos: left bottom;
  --circle-right-pos: right bottom;
}

.cool {
  width: 190px;
  height: 112px;

  background-image: var(--reflection), var(--display), var(--case),
    var(--circle), var(--circle), var(--body);

  background-size: var(--reflection-size), var(--display-size), var(
      --case-size
    ), var(--circle-size), var(--circle-size), var(--body-size);

  background-position: var(--reflection-pos), var(--display-pos), var(
      --case-pos
    ), var(--circle-left-pos), var(--circle-right-pos), var(--body-pos);

  background-repeat: no-repeat;

  /*outline: solid 1px;*/
}

See the Pen Single Div by Ahmad Shadeed (@shadeed) on CodePen.

Blending Multiple Backgrounds

Having multiple backgrounds is exciting when you can blend them. The simplest use-case that I can explain is desaturating an image. Consider that you have a background-image in CSS, and you want to turn it into black and white.

.hero {
  background:
    linear-gradient(#000, #000),
    url("landscape.jpg") center/cover;
  background-blend-mode: color;
}

The End

That’s a wrap. Do you have a comment or a suggestion? Please feel free to ping me on @shadeed9.

Thank you for reading.

I’m writing an ebook

I’m excited to let you know that I’m writing an ebook about Debugging CSS.

If you’re interested, head over to debuggingcss.com and subscribe for updates about the book.