You Don’t Need JavaScript for That!

Share this article

Web development today can be a whirlwind of various technologies, and even the simplest of widgets can often be complex under the hood.

With that in mind, I’d like to focus on a variety of things you can do with just HTML and CSS, no JavaScript required. Why, you ask? While some of these solutions may not be practical for every use case, they do inspire outside-the-box thinking that promotes lowered complexity, and a wider array of browser support. Here are a few cool things you can do without having to write a single line of JavaScript.

Building a Tabs Widget

We’ve all seen how the checkbox hack can be used for interactivity without JavaScript, but unfortunately, this comes at a cost to accessibility. So instead of another checkbox tutorial, I’d like to show how you can create an accessible tabs widget using the :focus pseudo-class in CSS.

Using :focus

The :focus pseudo-class is used to target an element that has received focus by the user (either by using the keyboard or the mouse). It is supported in every browser including IE8+. Additionally, you can apply a :focus state to any HTML element as long as you give it a tabindex attribute.

Using the tabindex Attribute

HTML’s tabindex attribute indicates if an element can receive focus. It can take several values, including a negative value, zero, or a positive value. Each of these values determines what order an element should be focused on.

Demo for the Tabs Widget

See the Pen Pure CSS Tabs Widget by SitePoint (@SitePoint) on CodePen.

In the HTML, each tab is a button with the content for each tab inside of a paragraph element. Each paragraph element is hidden, then set to position: absolute so that the content will display in the same area for each tab. The first button element has the autofocus attribute, so that the first tab will be visible on the initial page load. Each tab is wrapped in a div, and each div is given a tabindex value, which allows the <div> to be focusable.

As for the CSS, each button is set to display: inline-block, allowing for the tabs to appear side by side. We apply the :focuspsuedo-class to the button and use the adjacent sibling selector to show the related paragraph element when the button is focused. I’ve also added focus styles to the tab’s container div, which means that the tab will keep its focused state until the user clicks outside the entire widget.

Caveats for the Tabs Widget

Because this widget depends on the :focus psuedo-class, the tabbed content will be visible only when the tabs have a focused state. This means that the user will always have to click on a tab to see content. The autofocus attribute does allow one of the tabs to be visible on initial page load, but as soon as the user interacts with the page, the focus will be lost.

Browser Support for the Tabs Widget

I’ve tested this in IE8, and everything works as expected, except for the autofocus attribute, being that it’s an HTML5 feature. Chrome, Firefox, and Opera also work as expected, but the demo does not work in Safari unless the tab key is being used to apply focus. In the following demo the :focus pseudo-class doesn’t work in any of the versions of Safari that I’ve tested, which I suspect is due to a WebKit bug. I haven’t found a way around this issue, but as long as the WebKit bug is addressed, this technique should work just fine when the user clicks on the tabs.

Overall, the :focus pseudo-class can be a great way to add functionality to HTML and CSS, without having to invoke the use of JavaScript. If you enjoyed this demo, be sure to leave a comment, and more importantly, file a bug with Safari!

Building an Image Slider

If you need a simple static site with an image slider, a CSS only approach is a great way to keep your website fast an light. Let’s look at a quick example.

HTML and CSS for the Slider

We start with an outer container using a section element with a class of slideshow. Inside is a slideshow container where the images are placed. This slideshow also works with content other than images. To highlight that, we have a div with a class of text-container that is used to hold our non-image content.

The outermost container of the demo has a fixed width, and its overflow property is set to “hidden”. The container inside of this, which holds our slide content, has a much larger width, so that the images and text content can be placed next to each other without wrapping to a new line. It’s important to note that this container has to be exactly as wide as our slide content, or else the slides won’t transition properly.

Using CSS Animation

The slide class is where we apply the animation. The animation uses the translateX property to drag the long row of content across the outer container, which forms a mask, simulating the transition of slides.

The animation timing is one of the most important factors here. To get an even number of seconds between slide transitions, we need to multiply our desired transition time by the number of slides in our slider. Here we have four slides, and our desired transition is six seconds per slide – so our animation time needs to be 24 seconds long before it repeats. The infinite repetition is controlled by the “infinite” value on the animation-iteration-count property.

Setting up the Keyframes for this animation can be tedious. The goal is to get the animation to look like it pauses for each image, even though it never really does. To do this we need to define at least two empty keyframes per slide. This creates the pause effect, because the keyframes define key intervals in which the translateX property does not update. You can see this in the demo on line 66 of the CSS.

As an added bonus, hovering over the slider will pause the animation. This is done by setting the animation-play-state property to “paused” when targeting the slideshow-container element’s :hover state.

The Image Slider Demo

See the Pen Pure CSS Image Slider by SitePoint (@SitePoint) on CodePen.

Browser Support for the Image Slider

Works as expected in all browsers including IE10 and up!

Creating Icons with File Type Indicators

A while ago I was working on a WordPress site when I came across a potentially challenging design. In this case, different icons were needed to represent links based on their file types. This was a great time to present a JavaScript-free solution on a JavaScript-heavy website. The following demo shows how to get information from a block of HTML and display it with the CSS content property.

HTML and CSS for the File Type Icons

In this demo, I’m using data attributes to display the type of file that the user will be redirected to when they click the link.

The CSS content property takes as a value an attr() function that allows us to get the value of our HTML data attribute. Using the ::after pseudo-element, we create a small black bar that holds the tet in the content property, and we position it to display on the left side of our icon.

The CSS attr() function represents an exciting part of the specification, but currently does not have any browser support for use outside of the content property.

File Type Icons Demo

See the Pen File Type Icons with Data Attributes by SitePoint (@SitePoint) on CodePen.

Browser Support for the File Type Icons

I was surprised to find that this demo worked in every browser I tested it in, except for IE8 of course!

Conclusion

It’s becoming more common for developers to build things without JavaScript. These might not be great solutions for all use cases, but they’re options to consider and learning the concepts involved can deepen our understanding of CSS.

Frequently Asked Questions (FAQs) about CSS and JavaScript

Can I create interactive web elements without using JavaScript?

Absolutely! While JavaScript is a powerful tool for creating interactive web elements, it’s not the only option. CSS (Cascading Style Sheets) can also be used to create a variety of interactive elements, such as tabs, sliders, and carousels. By using CSS, you can reduce the load time of your website and improve its performance.

How can I create a CSS carousel slider without JavaScript?

Creating a CSS carousel slider without JavaScript involves using the CSS :target selector. This selector allows you to style an element that has been targeted by a link. By using this selector, you can create a carousel slider that rotates through different content when a user clicks on a link.

What are the benefits of using CSS over JavaScript for web development?

CSS has several advantages over JavaScript for web development. First, CSS is generally faster and more efficient than JavaScript, which can improve the performance of your website. Second, CSS is easier to learn and use than JavaScript, making it a great choice for beginners. Finally, CSS is more compatible with older browsers than JavaScript, ensuring that your website will work properly for all users.

Can I create navigation tabs using only CSS?

Yes, you can create navigation tabs using only CSS. This can be done using the CSS :checked pseudo-class selector. This selector allows you to style an element when it is in a certain state, such as when a checkbox is checked. By using this selector, you can create navigation tabs that change content when a user clicks on a tab.

How can I create an automatic image slider using only HTML and CSS?

Creating an automatic image slider using only HTML and CSS involves using the CSS animation property. This property allows you to create animations by changing the CSS properties of an element over time. By using this property, you can create an image slider that automatically rotates through different images.

What are some common challenges when creating interactive web elements with CSS?

While CSS is a powerful tool for creating interactive web elements, it does have some limitations. For example, CSS animations can be more complex to create than JavaScript animations. Additionally, CSS does not have the same level of interactivity as JavaScript, which can limit what you can do with your web elements.

Can I use CSS to create interactive web elements for mobile devices?

Yes, you can use CSS to create interactive web elements for mobile devices. CSS is fully compatible with all modern mobile browsers, and you can use media queries to create responsive designs that adapt to different screen sizes.

How can I improve the performance of my website using CSS?

There are several ways to improve the performance of your website using CSS. First, you can use CSS to create lightweight, efficient designs that load quickly. Second, you can use CSS to create animations and transitions that are smoother and more efficient than JavaScript animations. Finally, you can use CSS to create responsive designs that adapt to different screen sizes, improving the user experience on mobile devices.

Can I use CSS to create complex animations?

While CSS is not as powerful as JavaScript for creating complex animations, it is still capable of creating a wide range of animations. By using the CSS animation property, you can create animations that change the CSS properties of an element over time. This allows you to create a variety of animations, from simple transitions to complex sequences.

How can I learn more about using CSS for web development?

There are many resources available for learning about CSS for web development. Online tutorials, courses, and forums can provide a wealth of information on the subject. Additionally, practicing by creating your own web elements can be a great way to learn and improve your skills.

Tim EvkoTim Evko
View Author

Tim Evko is a front end web developer from New York, with a passion for responsive web development, Sass, and JavaScript. He lives on coffee, CodePen demos and flannel shirts.

css attrcss image slidercss slideshowcss tab switchercss tabslearn-advanced-cssLouisL
Share this article
Read Next
A Deep Dive into Building Enterprise grade Generative AI Solutions
A Deep Dive into Building Enterprise grade Generative AI Solutions
Suvoraj Biswas
LocalXpose: The Most Useful Tool for Developers to Share Localhost Online
LocalXpose: The Most Useful Tool for Developers to Share Localhost Online
SitePoint Sponsors
8 AI Tips for Web Developers (and Their Careers)
8 AI Tips for Web Developers (and Their Careers)
Jens Oliver Meiert
How to Make a Simple JavaScript Quiz
How to Make a Simple JavaScript Quiz
Yaphi BerhanuJames Hibbard
Best React UI Component Libraries
Best React UI Component Libraries
Kaarle Varkki
Windows Subsystem for Linux 2 (WSL2): The Complete Tutorial for Windows 10 & 11
Windows Subsystem for Linux 2 (WSL2): The Complete Tutorial for Windows 10 & 11
Craig Buckler
Automating Vultr Cloud Infrastructure with Terraform
Automating Vultr Cloud Infrastructure with Terraform
Vultr
Advanced Web Deployment With Plesk on Vultr
Advanced Web Deployment With Plesk on Vultr
Vultr
Building A 300 Channel Video Encoding Server
Building A 300 Channel Video Encoding Server
John O’Neill
Five Ways to Lazy Load Images for Better Website Performance
Five Ways to Lazy Load Images for Better Website Performance
Maria Antonietta Perna
Building a Telemedicine Platform with AI-Powered Diagnostics Using Vultr
Building a Telemedicine Platform with AI-Powered Diagnostics Using Vultr
Vultr
Create a Toggle Switch in React as a Reusable Component
Create a Toggle Switch in React as a Reusable Component
Praveen KumarMichael Wanyoike
Comparing Docker and Podman: A Guide to Container Management Tools
Comparing Docker and Podman: A Guide to Container Management Tools
Vultr
How to Deploy Flask Applications on Vultr
How to Deploy Flask Applications on Vultr
Vultr
A Comprehensive Guide to Understanding TypeScript Record Type
A Comprehensive Guide to Understanding TypeScript Record Type
Emmanuel Onyeyaforo
Top 7 High-Paying Affiliate Programs for Developers and Content Creators
Top 7 High-Paying Affiliate Programs for Developers and Content Creators
SitePoint Sponsors
How to integrate artificial intelligence into office software: the ONLYOFFICE Docs case study
How to integrate artificial intelligence into office software: the ONLYOFFICE Docs case study
SitePoint Sponsors
Momento Migrates Object Cache as a Service to Ampere Altra
Momento Migrates Object Cache as a Service to Ampere Altra
Dave Neary
Dev Hackathon: Reusable Creativity on Wix Studio
Dev Hackathon: Reusable Creativity on Wix Studio
SitePoint Sponsors
10 Amazing Web Developer Resume Examples for Different Web Dev Specializations
10 Amazing Web Developer Resume Examples for Different Web Dev Specializations
SitePoint Sponsors
How to Build Lightning Fast Surveys with Next.js and SurveyJS
How to Build Lightning Fast Surveys with Next.js and SurveyJS
Gavin Henderson
45 Visual Studio Code Shortcuts for Boosting Your Productivity
45 Visual Studio Code Shortcuts for Boosting Your Productivity
Shahed Nasser
Google Cloud Is the New Way to the Cloud
Google Cloud Is the New Way to the Cloud
SitePoint Sponsors
Understanding Vultr Content Delivery Networks (CDNs)
Understanding Vultr Content Delivery Networks (CDNs)
Vultr
Effortless Content Publishing: A Developer’s Guide to Adobe Experience Manager
Effortless Content Publishing: A Developer’s Guide to Adobe Experience Manager
SitePoint Sponsors
From Idea to Prototype in Minutes: Claude Sonnet 3.5
From Idea to Prototype in Minutes: Claude Sonnet 3.5
Zain Zaidi
Essential Plugins for WordPress Developers: Top Picks for 2024
Essential Plugins for WordPress Developers: Top Picks for 2024
SitePoint Sponsors
WebAssembly vs JavaScript: A Comparison
WebAssembly vs JavaScript: A Comparison
Kaan Güner
The Functional Depth of Docker and Docker Compose
The Functional Depth of Docker and Docker Compose
Vultr
How Top HR Agencies Build Trust Through Logo Designs
How Top HR Agencies Build Trust Through Logo Designs
Evan Brown
Leveraging Progressive Web Apps (PWAs) for Enhanced Mobile User Engagement
Leveraging Progressive Web Apps (PWAs) for Enhanced Mobile User Engagement
SitePoint Sponsors
10 Artificial Intelligence APIs for Developers
10 Artificial Intelligence APIs for Developers
SitePoint Sponsors
The Ultimate Guide to Navigating SQL Server With SQLCMD
The Ultimate Guide to Navigating SQL Server With SQLCMD
Nisarg Upadhyay
Retrieval-augmented Generation: Revolution or Overpromise?
Retrieval-augmented Generation: Revolution or Overpromise?
Kateryna ReshetiloOlexandr Moklyak
How to Deploy Apache Airflow on Vultr Using Anaconda
How to Deploy Apache Airflow on Vultr Using Anaconda
Vultr
Cloud Native: How Ampere Is Improving Nightly Arm64 Builds
Cloud Native: How Ampere Is Improving Nightly Arm64 Builds
Dave NearyAaron Williams
How to Create Content in WordPress with AI
How to Create Content in WordPress with AI
Çağdaş Dağ
A Beginner’s Guide to Setting Up a Project in Laravel
A Beginner’s Guide to Setting Up a Project in Laravel
Claudio Ribeiro
Enhancing DevSecOps Workflows with Generative AI: A Comprehensive Guide
Enhancing DevSecOps Workflows with Generative AI: A Comprehensive Guide
Gitlab
Creating Fluid Typography with the CSS clamp() Function
Creating Fluid Typography with the CSS clamp() Function
Daine Mawer
Comparing Full Stack and Headless CMS Platforms
Comparing Full Stack and Headless CMS Platforms
Vultr
7 Easy Ways to Make a Magento 2 Website Faster
7 Easy Ways to Make a Magento 2 Website Faster
Konstantin Gerasimov
Powerful React Form Builders to Consider in 2024
Powerful React Form Builders to Consider in 2024
Femi Akinyemi
Quick Tip: How to Animate Text Gradients and Patterns in CSS
Quick Tip: How to Animate Text Gradients and Patterns in CSS
Ralph Mason
Sending Email Using Node.js
Sending Email Using Node.js
Craig Buckler
Creating a Navbar in React
Creating a Navbar in React
Vidura Senevirathne
A Complete Guide to CSS Logical Properties, with Cheat Sheet
A Complete Guide to CSS Logical Properties, with Cheat Sheet
Ralph Mason
Using JSON Web Tokens with Node.js
Using JSON Web Tokens with Node.js
Lakindu Hewawasam
How to Build a Simple Web Server with Node.js
How to Build a Simple Web Server with Node.js
Chameera Dulanga
Building a Digital Fortress: How to Strengthen DNS Against DDoS Attacks?
Building a Digital Fortress: How to Strengthen DNS Against DDoS Attacks?
Beloslava Petrova
Crafting Interactive Scatter Plots with Plotly
Crafting Interactive Scatter Plots with Plotly
Binara Prabhanga
GenAI: How to Reduce Cost with Prompt Compression Techniques
GenAI: How to Reduce Cost with Prompt Compression Techniques
Suvoraj Biswas
How to Use jQuery’s ajax() Function for Asynchronous HTTP Requests
How to Use jQuery’s ajax() Function for Asynchronous HTTP Requests
Aurelio De RosaMaria Antonietta Perna
Quick Tip: How to Align Column Rows with CSS Subgrid
Quick Tip: How to Align Column Rows with CSS Subgrid
Ralph Mason
15 Top Web Design Tools & Resources To Try in 2024
15 Top Web Design Tools & Resources To Try in 2024
SitePoint Sponsors
7 Simple Rules for Better Data Visualization
7 Simple Rules for Better Data Visualization
Mariia Merkulova
Cloudways Autonomous: Fully-Managed Scalable WordPress Hosting
Cloudways Autonomous: Fully-Managed Scalable WordPress Hosting
SitePoint Team
Best Programming Language for AI
Best Programming Language for AI
Lucero del Alba
Quick Tip: How to Add Gradient Effects and Patterns to Text
Quick Tip: How to Add Gradient Effects and Patterns to Text
Ralph Mason
Logging Made Easy: A Beginner’s Guide to Winston in Node.js
Logging Made Easy: A Beginner’s Guide to Winston in Node.js
Vultr
How to Optimize Website Content for Featured Snippets
How to Optimize Website Content for Featured Snippets
Dipen Visavadiya
Psychology and UX: Decoding the Science Behind User Clicks
Psychology and UX: Decoding the Science Behind User Clicks
Tanya Kumari
Build a Full-stack App with Node.js and htmx
Build a Full-stack App with Node.js and htmx
James Hibbard
Digital Transformation with AI: The Benefits and Challenges
Digital Transformation with AI: The Benefits and Challenges
Priyanka Prajapat
Quick Tip: Creating a Date Picker in React
Quick Tip: Creating a Date Picker in React
Dianne Pena
How to Create Interactive Animations Using React Spring
How to Create Interactive Animations Using React Spring
Yemi Ojedapo
10 Reasons to Love Google Docs
10 Reasons to Love Google Docs
Joshua KrausZain Zaidi
How to Use Magento 2 for International Ecommerce Success
How to Use Magento 2 for International Ecommerce Success
Mitul Patel
5 Exciting New JavaScript Features in 2024
5 Exciting New JavaScript Features in 2024
Olivia GibsonDarren Jones
Tools and Strategies for Efficient Web Project Management
Tools and Strategies for Efficient Web Project Management
Juliet Ofoegbu
Choosing the Best WordPress CRM Plugin for Your Business
Choosing the Best WordPress CRM Plugin for Your Business
Neve Wilkinson
ChatGPT Plugins for Marketing Success
ChatGPT Plugins for Marketing Success
Neil Jordan
Managing Static Files in Django: A Comprehensive Guide
Managing Static Files in Django: A Comprehensive Guide
Kabaki Antony
The Ultimate Guide to Choosing the Best React Website Builder
The Ultimate Guide to Choosing the Best React Website Builder
Dianne Pena
Exploring the Creative Power of CSS Filters and Blending
Exploring the Creative Power of CSS Filters and Blending
Joan Ayebola
How to Use WebSockets in Node.js to Create Real-time Apps
How to Use WebSockets in Node.js to Create Real-time Apps
Craig Buckler
Best Node.js Framework Choices for Modern App Development
Best Node.js Framework Choices for Modern App Development
Dianne Pena
SaaS Boilerplates: What They Are, And 10 of the Best
SaaS Boilerplates: What They Are, And 10 of the Best
Zain Zaidi
Understanding Cookies and Sessions in React
Understanding Cookies and Sessions in React
Blessing Ene Anyebe
Enhanced Internationalization (i18n) in Next.js 14
Enhanced Internationalization (i18n) in Next.js 14
Emmanuel Onyeyaforo
Essential React Native Performance Tips and Tricks
Essential React Native Performance Tips and Tricks
Shaik Mukthahar
How to Use Server-sent Events in Node.js
How to Use Server-sent Events in Node.js
Craig Buckler
Five Simple Ways to Boost a WooCommerce Site’s Performance
Five Simple Ways to Boost a WooCommerce Site’s Performance
Palash Ghosh
Elevate Your Online Store with Top WooCommerce Plugins
Elevate Your Online Store with Top WooCommerce Plugins
Dianne Pena
Unleash Your Website’s Potential: Top 5 SEO Tools of 2024
Unleash Your Website’s Potential: Top 5 SEO Tools of 2024
Dianne Pena
How to Build a Chat Interface using Gradio & Vultr Cloud GPU
How to Build a Chat Interface using Gradio & Vultr Cloud GPU
Vultr
Enhance Your React Apps with ShadCn Utilities and Components
Enhance Your React Apps with ShadCn Utilities and Components
David Jaja
10 Best Create React App Alternatives for Different Use Cases
10 Best Create React App Alternatives for Different Use Cases
Zain Zaidi
Control Lazy Load, Infinite Scroll and Animations in React
Control Lazy Load, Infinite Scroll and Animations in React
Blessing Ene Anyebe
Building a Research Assistant Tool with AI and JavaScript
Building a Research Assistant Tool with AI and JavaScript
Mahmud Adeleye
Understanding React useEffect
Understanding React useEffect
Dianne Pena
Web Design Trends to Watch in 2024
Web Design Trends to Watch in 2024
Juliet Ofoegbu
Building a 3D Card Flip Animation with CSS Houdini
Building a 3D Card Flip Animation with CSS Houdini
Fred Zugs
How to Use ChatGPT in an Unavailable Country
How to Use ChatGPT in an Unavailable Country
Dianne Pena
An Introduction to Node.js Multithreading
An Introduction to Node.js Multithreading
Craig Buckler
How to Boost WordPress Security and Protect Your SEO Ranking
How to Boost WordPress Security and Protect Your SEO Ranking
Jaya Iyer
Understanding How ChatGPT Maintains Context
Understanding How ChatGPT Maintains Context
Dianne Pena
Building Interactive Data Visualizations with D3.js and React
Building Interactive Data Visualizations with D3.js and React
Oluwabusayo Jacobs
JavaScript vs Python: Which One Should You Learn First?
JavaScript vs Python: Which One Should You Learn First?
Olivia GibsonDarren Jones
13 Best Books, Courses and Communities for Learning React
13 Best Books, Courses and Communities for Learning React
Zain Zaidi
Get the freshest news and resources for developers, designers and digital creators in your inbox each week