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

推荐订阅源

D
DataBreaches.Net
S
Schneier on Security
T
The Exploit Database - CXSecurity.com
Webroot Blog
Webroot Blog
AI
AI
P
Palo Alto Networks Blog
Attack and Defense Labs
Attack and Defense Labs
WordPress大学
WordPress大学
月光博客
月光博客
阮一峰的网络日志
阮一峰的网络日志
Spread Privacy
Spread Privacy
T
Tor Project blog
罗磊的独立博客
小众软件
小众软件
S
Security Affairs
酷 壳 – CoolShell
酷 壳 – CoolShell
量子位
Apple Machine Learning Research
Apple Machine Learning Research
T
Threatpost
NISL@THU
NISL@THU
博客园_首页
PCI Perspectives
PCI Perspectives
大猫的无限游戏
大猫的无限游戏
IT之家
IT之家
N
News and Events Feed by Topic
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Forbes - Security
Forbes - Security
博客园 - 叶小钗
D
Darknet – Hacking Tools, Hacker News & Cyber Security
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Last Week in AI
Last Week in AI
L
LINUX DO - 热门话题
T
Threat Research - Cisco Blogs
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
腾讯CDC
Security Latest
Security Latest
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
The Cloudflare Blog
A
About on SuperTechFans
爱范儿
爱范儿
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
TaoSecurity Blog
TaoSecurity Blog
宝玉的分享
宝玉的分享
G
GRAHAM CLULEY
雷峰网
雷峰网
F
Full Disclosure
I
Intezer
Cloudbric
Cloudbric
博客园 - 三生石上(FineUI控件)
U
Unit 42

CSS Wizardry

Front-End’s Missing Metric: The TBT Window Meet Your Users Where They Are with Obs.js Better Browser Caching with No-Vary-Search font-family Doesn’t Fall Back the Way You Think What Is CSS Containment and How Can I Use It? When All You Can Do Is All or Nothing, Do Nothing Obs.js: Context-Aware Web Performance for Everyone Low- and Mid-Tier Mobile for the Real World (2025) The Fastest Site in the Tour de France Making Sense of the Performance Extensibility API Why Do We Have a Cache-Control Request Header? HTML Is Not a Programming Language… Build for the Web, Build on the Web, Build with the Web Licensing Code on CSS Wizardry A Layered Approach to Speculation Rules Designing (and Evolving) a New Web Performance Score Core Web Vitals Colours The Ultimate Contract Templates for Tech Consultants: Protect Your Business and Get Paid Optimising for High Latency Environments Cache Grab: How Much Are You Leaving on the Table? blocking=render: Why would you do that?! Correctly Configure (Pre) Connections The Three Cs: 🤝 Concatenate, 🗜️ Compress, 🗳️ Cache What Is the Maximum max-age? How to Clear Cache and Cookies on a Customer’s Device The Ultimate Low-Quality Image Placeholder Technique Core Web Vitals for Search Engine Optimisation: What Do We Need to Know? The HTTP/1-liness of HTTP/2 In Defence of DOM­Content­Loaded Site-Speed Topography Remapped Why Not document.write()? Speeding Up Async Snippets Critical CSS? Not So Fast! Measure What You Impact, Not What You Influence Optimising Largest Contentful Paint Measuring Web Performance in Mobile Safari Site-Speed Topography Speed Up Google Fonts Real-World Effectiveness of Brotli Performance Budgets, Pragmatically Lazy Pre-Browsing with Prefetch Making Cloud.typography Fast(er) Time to First Byte: What It Is and How to Improve It Self-Host Your Static Assets Tips for Technical Interviews Cache-Control for Civilians Bandwidth or Latency: When to Optimise for Which ITCSS × Skillshare What If? CSS and Network Performance The Three Types of Performance Testing Getting to Know a Legacy Codebase Image Inconsistencies: How and When Browsers Download Images Identifying, Auditing, and Discussing Third Parties My Digital Music Setup Measuring the Hard-to-Measure Finding Dead CSS The Fallacies of Distributed Computing (Applied to Front-End Performance) Ten Years Old Relative Requirements Airplanes and Ashtrays Performance and Resilience: Stress-Testing Third Parties Refactoring Tunnels Little Things I Like to Do with Git Writing Tidy Code Configuring Git and Vim Base64 Encoding & Performance, Part 2: Gathering Data Base64 Encoding & Performance, Part 1: What’s Up with Base64? Code Smells in CSS Revisited Typography for Developers Moving CSS Wizardry onto HTTPS and HTTP/2 Ack for CSS Developers A New Year, a New Focus Preparing Vim for Apple’s Touch Bar Choosing the Correct Average CSS Shorthand Syntax Considered an Anti-Pattern CSS Wizardry Newsletter Nesting Your BEM? Improving Perceived Performance with Multiple Background Images Continue Normalising Your CSS Pure CSS Content Filter Pragmatic, Practical, and Progressive Theming with Custom Properties Refactoring CSS: The Three I’s Speaker’s Checklist: Before and After Your Talk Improving Your CSS with Parker The Importance of !important: Forcing Immutability in CSS Mixins Better for Performance Managing Typography on Large Apps White October Events Workshop Partnership BEMIT: Taking the BEM Naming Convention a Step Further Travelling Like You Want to, When You Have To Contextual Styling: UI Components, Nesting, and Implementation Detail Subtleties with Self-Chained Classes Cyclomatic Complexity: Logic in CSS Immutable CSS Can CSS Be Too Modular? More Transparent UI Code with Namespaces When to use @extend; when to use a mixin The Specificity Graph CSS Wizardry Ltd.: Year 1 in review
Fully fluid, responsive CSS carousel
Harry Roberts · 2011-11-01 · via CSS Wizardry

Written by on CSS Wizardry.

Table of Contents

Independent writing is brought to you via my wonderful Supporters.

  1. Demo
  2. The fluidity
  3. CSS powered
  4. Update
    1. Wait, CSS?!

If you follow me on Twitter you’ll know I’ve been pretty enthused about this fluid CSS carousel of mine. There are two aspects to it; the fluidity and the CSS functionality.

Demo

The demo features photos of me, taken on various mountains by Suze. Cheers to her for the content.

The fluidity

Making a carousel fluid is actually ridiculously simple. Let us assume you have five panels. Remember that number!

A carousel is made up of three basic components:

  1. A viewport
  2. A wrapper for the panes
  3. A pane

Thus, our markup is:

<div class=carousel>

  <ul class=panes>

    <li>
      <h2>Pane 01 title</h2>
      <img src=pane-01.jpg alt="">
    </li>

    <li>
      <h2>Pane 02 title</h2>
      <img src=pane-02.jpg alt="">
    </li>

    <li>
      <h2>Pane 03 title</h2>
      <img src=pane-03.jpg alt="">
    </li>

    <li>
      <h2>Pane 04 title</h2>
      <img src=pane-04.jpg alt="">
    </li>

    <li>
      <h2>Pane 05 title</h2>
      <img src=pane-05.jpg alt="">
    </li>

  </ul>

</div>

Now, the viewport defines what we see, we slide our panes behind it and they poke through. We just slide these behind the viewport to show a certain amount at a time, et voilà; carousel. But, you all know how carousels work, right…?

To make this fluid is so simple. The viewport needs to fill its container, so this gets width:100%;. Easy.

One pane needs to fit nicely in the viewport, so this needs to occupy 100% of the viewport. With this in mind…

We have five panes, remember, so the ul needs a width of 500%. Five panes that are each the same width as the viewport gives us a width of 500%.

Now we know:

.carousel{
  width:100%;
}
.panes{
  width:500%;
}

So if .panes holds five panes, each pane should be 20% its width. This is where it might get a little confusing…

The viewport is 100% width, the wrapper is five times as big as that and each pane is one fifth the width of the wrapper.

Our code is left at:

/*------------------------------------*\
    $CAROUSEL
\*------------------------------------*/
.carousel{
    overflow:hidden;
    width:100%;
}
.panes{
    list-style:none;
    position:relative;
    width:500%; /* Number of panes * 100% */
    overflow:hidden; /* This is used solely to clear floats, it does not add functionality. */
        
    -moz-animation:carousel 30s infinite;
    -webkit-animation:carousel 30s infinite;
    animation:carousel 30s infinite;
}
.panes > li{
    position:relative;
    float:left;
    width:20%; /* 100 / number of panes */
}
.carousel img{
    display:block;
    width:100%;
    max-width:100%;
}
.carousel h2{
    font-size:1em;
    padding:0.5em;
    position:absolute;
    right:10px;
    bottom:10px;
    left:10px;
    text-align:right;
    color:#fff;
    background-color:rgba(0,0,0,0.75);
}

The basic equation for making a carousel with any number of panes is:

<pre><code>.carousel{
  width:100%;
}
.panes{
  width:<mark>100 * number of panes</mark>%;
}
.panes > li{
  width:<mark>100 / number of panes</mark>%;
}</code></pre>

So, a four-pane carousel would be:

<pre><code>.carousel{
  width:100%;
}
.panes{
  width:<mark>400</mark>%;
}
.panes > li{
  width:<mark>25</mark>%;
}</code></pre>

It really is that simple. That’s all there is to making a fluid carousel.

CSS powered

Okay, in this carousel I decided I was going to power it with CSS. This is super unorthodox so if you’re yelling WTF at your screen please read on!

It was going to be (and actually is) used on my good friend Sam Penrose’s new design portfolio, so knowing we had free reign and a little chance to experiment I decided to opt for a pure CSS solution.

This is simple in theory but the maths gets so tricky.

All we do is animate .panels from right to left then back again. We animate for a bit, we pause, we animate again, pause again and so on until it’s done. Then we loop it infinitely.

The CSS is:

@keyframes carousel{
    0%    { left:0; }
    11%   { left:0; }
    12.5% { left:-100%; }
    23.5% { left:-100%; }
    25%   { left:-200%; }
    36%   { left:-200%; }
    37.5% { left:-300%; }
    48.5% { left:-300%; }
    50%   { left:-400%; }
    61%   { left:-400%; }
    62.5% { left:-300%; }
    73.5% { left:-300%; }
    75%   { left:-200%; }
    86%   { left:-200%; }
    87.5% { left:-100%; }
    98.5% { left:-100%; }
    100%  { left:0; }
}

The numbers are so tricky to work with and if anyone can come up with a decent equation to describe it I would be so happy. I’ve got Nick on the job, but I’ve not worked it out yet; I can’t quite grasp the relation between five panes and the numbers above in a way that I could do some quick maths to work out the animations for a four-pane carousel.

The problem is that you have to know how many full moves and pauses are needed for a full iteration of the carousel (before it starts on its infinite loop), and then how to evenly space these numbers between 0 and 100%. My animations last for 1.5% and pause for 11%, these numbers are perfect for adding up to 100%.

Update

Massive thanks to Clay who’s worked out that the number of steps is 4n-3 and that the total time between start of one animation and the next is 100 / 2(n-1) (where n is the number of panes). See his full comment.

But, the code above will sort you out a perfect animation for a five panes so feel free to nab it! I’ll update if and when I crack some maths!

Wait, CSS?!

Using CSS for this is really, really unorthodox so comes with some massive caveats.

Do not use CSS to animate this carousel if:

  1. You require the contents of every pane to be visually accessible to the user.
  2. You require full browser support.
  3. You do not require interactions (like stopping the animation or clicking between panes).

If you are going to use this CSS-only method then ensure that:

  1. The user can still use the site fully without the contents of the panes.
  2. You are okay with older browsers not animating and just displaying the first pane.
  3. You do not want or require users to be able to interact with the carousel.

If you can’t use CSS then combine the fluidity above with plain ol’ trusty JS.

I will happily say that the fluidity is the most important, useful and impressive thing about this technique. Until I, or anyone, can get you a decent equation to substitute your numbers into, the CSS animations are too cumbersome and restrictive to be of large-scale use to most people.