The Linux Code

Applying CSS Styles to Safari Browser Only

As web developers, we often need to target specific browsers with CSS styling. Safari frequently requires its own special treatment to achieve consistent cross-browser experiences.

In this in-depth guide, you‘ll learn multiple techniques for applying styles exclusively to Safari using CSS, JavaScript, and other clever tricks.

By the end, you‘ll understand the nuances of styling for Safari and be able to build web apps optimized specifically for Apple‘s browser. Let‘s dive in!

Why Would You Want to Single Out Safari for Styling?

Before we look at how to target Safari, it‘s important to understand the motivations behind doing so. There are a few key reasons you may want to intentionally apply CSS only for Safari:

Safari Has Unique Rendering Behavior

Safari often renders elements slightly differently than other major browsers like Chrome, Firefox, and Edge. For example, margins, fonts, and grid layouts may display inconsistently.[1] These cross-browser differences can lead to frustrating styling bugs.

Using Safari-specific CSS overrides gives you more control to achieve pixel-perfect consistency across browsers.

Safari Supports Cutting Edge CSS Features First

Since Safari uses the WebKit rendering engine, it will often implement the latest experimental CSS properties and APIs before other browsers.

For example, Safari was one of the first to ship support for CSS Grid, Flexbox, Custom Properties, and other new capabilities. By leveraging those features only in Safari, you can provide an enhanced experience in that browser while avoiding compatibility issues in others.

Optimizing for iOS Web Apps

On iOS devices like iPhones and iPads, the only browser choice is Safari. So if you are building a web app primarily targeting iOS users, you‘ll want to customize the styling specifically for mobile Safari.

Safari on iOS supports some unique meta tags, viewport values, and other mobile-centric features. Fine-tuning for iOS can provide a seamless app-like experience.

Progressive Enhancement

Another school of thought is to use Safari-specific styling as a progressive enhancement. First build a solid baseline experience that works across all browsers. Then layer on enhancements like animations, shadows, and other bells and whistles just for capable browsers like Safari.

This allows you to maximize compatibility while still providing an elevated experience for targeted browsers.

Safari Market Share and Usage

So how popular is Safari exactly? Here are some statistics on Apple‘s browser market share:

  • On desktop, Safari has around 15% global usage, lower than Chrome, Firefox, and Edge but still considerable.[2]
  • On mobile, Safari dominates with over 50% usage on iPhone and iPads globally.[3]
  • In North America, Safari jumps to nearly 80% market share on mobile thanks to iPhone popularity.[4]

So while Safari may lag behind on desktop, it is by far the mobile browser of choice for millions of Apple device users worldwide. This makes optimizing the mobile experience critical.

Technique #1: Using -webkit Vendor Prefixes

The simplest way to target Safari is by using -webkit vendor prefixed CSS properties.

Safari and other WebKit-based browsers recognize these experimental -webkit- prefixes. So it provides an easy way to provide Safari-only styling.

For example:

This -webkit-appearance style will apply uniquely in Safari. Other major browsers will ignore that line completely.

You can use -webkit- prefixes for animations, gradients, transforms, and more cutting edge CSS features. This allows you to leverage those capabilities exclusively in Safari.

Here is an example applying a Safari-only gradient background:

This progressive enhancement approach will provide a simple #eee background across all browsers. But Safari will also render the more visually appealing gradient version.

One caution with vendor prefixes is browser support does eventually get patched in over time. So the styles may start applying more broadly in the future.

But as an easy short-term shortcut for Safari-specific styling, -webkit- prefixes are quite useful.

Technique #2: The ::i-block-chrome Pseudo-element

Safari also supports a non-standard pseudo-element ::i-block-chrome specifically for blocking rules from applying in Chrome.

We can leverage this to reverse-target Safari-only CSS:

Here the default color style will apply as blue in Chrome. But Safari will override it to red.

This approach is a bit more convoluted but can be handy for overwriting styles in just Safari. Do note browser support:

  • ::i-block-chrome works in Safari 10.1+
  • Chrome and other browsers will ignore it completely
  • Older Safari versions will fail silently without applying overrides

So be sure to test across browsers and provide fallback styling. But used judiciously, the ::i-block-chrome pseudo-element gives you another option for Safari-specific CSS.

Technique #3: @supports Feature Queries

CSS feature queries allow you to conditionally apply styles based on a browser‘s capability support. We can leverage @supports to target Safari like so:

This will restrict the CSS rules to only apply in browsers that recognize the -webkit-appearance property. That matches the WebKit family including Safari.

The major advantage of @supports is it defensive and resilient to browser changes. If other browsers eventually implement the -webkit- prefix, they will automatically apply the styles rather than breaking.

Let‘s look at an example rounding the corners of an image only in supporting browsers:

The rounded corners will display in Safari, while gracefully degrading to square corners in other browsers.

One thing to note is Firefox does not support @supports queries. So avoid relying on it exclusively. But combined with other techniques, it provides robustSafari targeting.

Technique #4: User Agent Detection in JavaScript

For ultimate control, you can use JavaScript to detect the user‘s browser agent string and conditionally apply a class to the <html> tag:

Then write CSS rules that only apply to that class:

This gives you unlimited precision to target styles. But do be careful:

  • User agent sniffing can be unreliable and prone to spoofing
  • Adds JavaScript dependency for styling
  • More complex code maintenance

So in general, opt for progressive enhancement techniques in CSS before JavaScript detection. But having the option available can be helpful in certain cases.

Browser Compatibility for Safari CSS Hacks

To use these techniques effectively, you‘ll need to understand which browser versions support each hack or workaround. Here are some key compatibility notes:

So some important takeaways:

  • -webkit- prefixes workgreat back through Safari 4+ but may get patched in other browsers over time
  • ::i-block-chrome won‘t work in Safari below 10.1 – test carefully
  • No Firefox support for @supports – don‘t rely on it alone
  • JS UA detection works across browsers but can be unreliable

Always check caniuse.com to test browser support for specific CSS features. Test your site in older Safari versions to watch for quirks.

Debugging and Testing Tips

Getting Safari-only styling right can take some trial and error. Here are some tips to smooth out the process:

Use BrowserStack

Sign up for BrowserStack or a similar cloud-based browser testing suite. They make it easy to access old and mobile Safari versions across operating systems for testing.

Use the WebKit Debug Mode

In Safari developer tools, you can toggle "Web Inspector Debug Mode". This will force Safari to use the WebKit rendering engine instead of Nitro for more debugging fidelity.

Test iOS Devices

Acquire some used iPhones or iPod Touches to test directly on real iOS hardware. This will expose mobile Safari quirks you can‘t catch in emulators.

Simulate Mobile in DevTools

In Chrome or Firefox devtools, you can simulate a mobile Safari user agent. Combined with device mode, this mimics Safari on iPhone well for basic testing.

Feature Detection

Use libraries like Modernizr to detect feature support at runtime. Apply browser classes to the html tag to assist styling.

Audit with Lighthouse

Google Lighthouse provides an audit for detecting CSS prefixes needed for cross-browser support. Super handy!

Conditional Comment Debug Code

Use IE-syntax conditional comments to target debug info just to Safari during development:

Following this comprehensive testing approach helps catch styling quirks early across various Safari environments.

Author Background on Cross-Browser Styling

Before we conclude, I wanted to provide some background on my experience wrestling with Safari and cross-browser CSS issues:

I‘ve been working on web design and development for over 15 years now. In that time, I‘ve helped build and maintain dozens of sites targeted at multi-platform users.

These have included:

  • Responsive websites serving millions of global visitors across browsers.
  • Web apps focused on iOS and Android mobile users.
  • Enterprise admin systems needing broad compatibility.
  • Video streaming sites requiring high performance.
  • And many more!

Needless to say, I‘ve run into my fair share of Safari CSS problems over the years. Simple things like button styling, grids, and animations that break on Apple‘s browser.

I‘ve also built web apps specifically for Safari on iPhones and iPads. This involved deep Safari platform research and finding workarounds to enable great mobile user experiences.

Additionally, I stay up-to-date by reading release notes, attending web conferences, and constantly testing new CSS features in browsers. I contribute to open source CSS tools and enjoy sharing front-end knowledge with other developers.

While cross-browser CSS is notoriously tricky, I love the challenge of mastering Safari quirks and finding innovative solutions. Hopefully this guide has shared some helpful secrets for wrangling Safari through its past and future evolutions!

Key Takeaways and Recommendations

Let‘s wrap up with some final tips for applying CSS selectively to Safari:

  • Audit browser usage data to see if Safari optimization is worthwhile for your site. If most of your traffic is Chrome on desktop, targeting Safari may be unnecessary.
  • For the best compatibility and performance , stick to progressive enhancement techniques in CSS before JavaScript detection.
  • Utilize -webkit vendor prefixes for cutting edge styles and experimental APIs in modern Safari versions.
  • For debugging , leverage browser dev tools, emulators, BrowserStack, and feature detection. Test early, test often!
  • Beware mobile Safari – the iOS browser has lots of unique quirks, so thoroughly test on real devices.
  • Understand that browser landscapes evolve quickly . Safari-only hacks today may apply more broadly someday. Build defensively.
  • There are always tradeoffs when targeting specific browsers . Strive for maximum compatibility and minimum complexity.

While selectively styling for Safari can be beneficial, also consider if focusing efforts on general cross-browser robustness may better serve your project and users.

Often the best solution is combining great default styling with judicious enhancements just for capable browsers like Safari. This progressive approach typically yields the best real-world results.

Nonetheless, using the techniques outlined in this guide, you can tap into Safari exclusive capabilities today and optimize sites for Apple‘s ecosystem. The web is a wild platform filled with quirks – by understanding them deeply, we can deliver the best possible experiences to users on the browsers they love.

So get out there, test some Safari CSS hacks, and push the web forward!

  • W3C Specifications
  • CanIUse.com
  • MDN Web Docs

You maybe like,

Related posts, @import and partials in sass | explained.

Supercharging Sass with @import and Partials Hey friends! As front-end developers, we love Sass. It makes writing CSS enjoyable with its arsenal of features –…

10 Must-Play HTML5 Games That Showcase the Future of Web Gaming

HTML5 has ignited a revolution in game development. With its extensive markup language, powerful JavaScript APIs, and support for accelerated graphics through Canvas and WebGL,…

3 Easy Ways to Place Images Side by Side in HTML & CSS

Placing images side-by-side is a common task in web design. It allows you to create an appealing layout with photos, illustrations, icons, and more. In…

A Complete Guide to Ordered Lists in HTML: Usage, Customization, and Best Practices

Ordered lists allow you to easily structure numbered and sequenced content in your web pages. This comprehensive guide will teach you how ordered lists work…

A Complete Guide to the Powerful CSS Inset Property

The CSS inset property gives developers a concise way to set all inner offsets on an element simultaneously. When browser support improves, inset could eliminate…

A Complete Guide to Using Google Icons in Your Web Projects

Icons are a vital part of creating intuitive and visually appealing web interfaces. Implemented well, icons enhance the user experience by communicating complex ideas quickly…

A rather geeky/technical weblog, est. 2001, by Bramus

CSS @​supports rules to target only Firefox / Safari / Chromium

Yesterday I took some time to rework my Houdini-powered CSS Gradient Border Animation Demo to include a fallback for non-Houdini browsers.

The plan of attack was pretty straightforward:

  • Manual frame-by-frame animations for non-Houdini browsers
  • Automagic Houdini-powered animations for browser with @property support

Only problem with that approach is that there’s currently no way to use @supports to directly detect whether a browser supports Houdini’s @property or not , so I got creative with @supports …

Houdini is a set of low-level APIs that exposes parts of the CSS engine, giving developers the power to extend CSS by hooking into the styling and layout process of a browser’s rendering engine. Houdini is a group of APIs that give developers direct access to the CSS Object Model (CSSOM), enabling developers to write code the browser can parse as CSS, thereby creating new CSS features without waiting for them to be implemented natively in browsers.

It really is magic, hence it's name Houdini. I'd recommend this slidedeck and this video to get you started

Join the Conversation

' src=

  • Pingback: Web Design & Development News: Collective #668 | Codrops

Hi Bramus, it looks like this is not working. I have both Brave (Chromium) and Safari open next to each other on my desktop and the “combined demo” are both showing blue.. (Safari should be red?). Has something changed with the specs on either of these browsers since 2021?

As mentioned in the post, these tests are really fragile and could stop working any time. I guess that time has come, as more browsers support many new features.

Leave a comment

Cancel reply.

Your email address will not be published. Required fields are marked *

Notify me of followup comments via e-mail. You can also subscribe without commenting.

This site uses Akismet to reduce spam. Learn how your comment data is processed .

w3docs logo

  • Password Generator
  • HTML Editor
  • HTML Encoder
  • JSON Beautifier
  • CSS Beautifier
  • Markdown Convertor
  • Find the Closest Tailwind CSS Color
  • Phrase encrypt / decrypt
  • Browser Feature Detection
  • Number convertor
  • CSS Maker text shadow
  • CSS Maker Text Rotation
  • CSS Maker Out Line
  • CSS Maker RGB Shadow
  • CSS Maker Transform
  • CSS Maker Font Face
  • Color Picker
  • Colors CMYK
  • Color mixer
  • Color Converter
  • Color Contrast Analyzer
  • Color Gradient
  • String Length Calculator
  • MD5 Hash Generator
  • Sha256 Hash Generator
  • String Reverse
  • URL Encoder
  • URL Decoder
  • Base 64 Encoder
  • Base 64 Decoder
  • Extra Spaces Remover
  • String to Lowercase
  • String to Uppercase
  • Word Count Calculator
  • Empty Lines Remover
  • HTML Tags Remover
  • Binary to Hex
  • Hex to Binary
  • Rot13 Transform on a String
  • String to Binary
  • Duplicate Lines Remover

How to Fix CSS Issues on Safari

Different browsers serve the web page content differently which can cause problems while using some CSS properties. To solve this kind of issues, there is a simple solution that will help you with 90 percent of cases.

Although many programmers face some difficulties when Safari doesn’t support CSS properties, these properties work fine in other browsers.

Displaying properties in Safari

There is a CSS appearance property used to display an element using a platform-native styling based on the users' operating system's theme. To make it work on Safari, we must set the appearance property to its "none" value. Also, use -WebKit- and -Moz- vendor prefixes.

Let’s see an example, where we use this trick to make the border-radius property work on Safari without any problem.

Example of making the border-radius property work on Safari:

The background-color property may also have the cause problem on Safari. Let’s see one more example.

Example of making the background-color property work on Safari:

Related resources.

  • CSS appearance Property
  • HTML Basics
  • Javascript Basics
  • TypeScript Basics
  • React Basics
  • Angular Basics
  • Sass Basics
  • Vue.js Basics
  • Python Basics
  • Java Basics
  • NodeJS Basics

Change CSS rules only in Safari

FabioRosado Saturday 5th, May 2020 2 mins to read 0 Like 0 Comment

How to apply css rules to safari only

The solution.

While working on Thumbs Up News , I've noticed a strange UI bug that happened only on Safari, when the screen was smaller than 900px height-wise. All the other browsers where okay, but the subscribe button was broken. The border was pushed up outside the area of the button and was now between the two elements of the menu. This only happened when a user clicked the categories button and the sub-menu expanded. I'm assuming that this happens because Apple wants space for its bottom menu?

The mobile menu is set on a fixed position. It seems that Safari will change either the padding, the margin or just some border rules when that fixed element doesn't have enough space vertically to show some space under the last element. My first thought was to use the -webkit rule to increase the padding on the button. Using that rule fixed the issue on Safari but broke on Chrome and this is when my search on how to apply CSS rules to a specific browser started.

After searching for a while, I've come across this article written by Ryan - CSS3 Media Query to target only Internet Explorer (from IE6 to IE11+), Firefox, Chrome, Safari and/or Edge , if you scroll down you come to this little hack that works on Safari 10.1+.

I am using Sass on Thumbs Up News and that means I can't have an empty @media rule. But this was a great starting point for coming up with a solution. I've removed the empty media query to see if the rule would work on Safari and not on any other browser. Surprise, surprise, it worked! Now I decided to play around with the media query rule a bit more, to see what works and what doesn't work.

The Safari only rule hack has two parts. You need to use a unit that is not supported by Safari - dpcm , dpi , dppx and you need to set that media query to not all . The not all rule is important so chrome doesn't pick it up.

After testing different things and playing around with the media query, I've come to the final solution. I've also added a rule to trigger the CSS only when the screen is smaller than 900px high, because we don't want the menu to be broken on a larger screen.

That's all there is to get a media query work on Safari only. I'm still wondering why this trick works and would love to know why, so if you know the answer please let me know!

Webmentions

You might also like these.

A lot of sites make the first letter of a paragraph spread to multiple lines, let me share with you how you can do it.

Make the first letter spread multiple lines

Make the first letter spread multiple lines

Nx makes it easy to work with monorepost, this article will show you how you can use Nx for your projects and talks about some basic commands that will help you.

Getting started with Nx

Getting started with Nx

How to set up an UI element persistent in Gatsby to allow users from Landing in Tech to listen to the latest episode, when navigating the site.

How to make a UI element persistent in Gatsby

How to make a UI element persistent in Gatsby

How to create a function to filter articles by tag. On this post I am using the javascript filter method to filter all articles.

How to filter all MDX articles by tags

How to filter all MDX articles by tags

CSS Reference

Css properties, css browser support reference, css reference with browser support.

The table below lists all CSS properties and how each property is supported in the different browsers:

The number to the right of the browser icon indicates in which browser version the property was first supported.

Icon Explanations

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

Controls the level of style and functionality of the site, a lower fidelity meaning less bandwidth, battery, and CPU usage. Learn more .

Custom Style Sheets in Safari

I first heard mention of adding a custom style sheet in Safari a couple months back. I honestly can’t remember where I saw it but I was reading something and, in passing, the author mentioned the idea of hiding the right sidebar on Twitter using a custom style sheet in Safari. This thing:

Screenshot of the right sidebar of twitter.com, circa Jan 2021.

It’s funny how you sometimes miss the entire point of someone’s writing and selectively remember what you want, in this case “hey, I can hide that dumb module on Twitter with little effort?” I’d like to say that I have the self-discipline to avoid clicking on anything in that module, but unfortunately I am not that strong of a person. Sometimes I just get bored and something there makes me think “oh, hmm, I wonder...” and then I click it. It’s one of those things where, if it wasn’t there, it wouldn’t be a problem. Like keeping cookies right next to your desk. But it’s frictionless and easy and RIGHT THERE that I succumb. But I digress. My weaknesses are not on trial in this post.

The thought hit me: “hey I should hide that right sidebar on twitter.com using a custom style sheet in Safari!” So I did. And then I moved on with life. I never thought to write a post about it because, you know, custom style sheets in a browser? That’s old news.

But then, I recently found this post published in November of 2020 about customizing your browsing experience using custom style sheets and thought “I guess this isn’t old news just quite yet.” Plus I’m trying to write a lot more this year , so here we are.

Note: it’s worth mentioning that hiding the right sidebar in twitter isn’t a novel idea. Craig Hockenberry created a Safari extension that’ll do it for you called “Fixerrific”. Granted, like my custom style sheet, this removes the entire right sidebar, including the search box which you might actually find useful. That said, you can still access the search functionality on twitter by going to the Explore tab.

How I Did It

First off, Safari lets you specify a custom style sheet.

Screenshot of Safari’s preferences pane where you can select a custom style sheet.

In case you don’t know, a custom style sheet is a bunch of CSS rules that you get to specify and then the browser will apply them to every single web page you visit .

The first thing I needed to do was open twitter.com and find out what type of CSS rule I could write to target that right sidebar. I can tell you, it wasn’t easy. Twitter has a bunch of generated classes names, which I’m assuming are quite dynamic, so finding a rule that would target the right sidebar and not change in the near future seemed like it might be tough. But then I found it: a DOM node which encompassed the entire right sidebar that had a very specific attribute data-testid="sidebarColumn" .

Screenshot of twitter.com in Safari with the developer tools open and targeting a parent DOM node of the right sidebar.

I can’t say for sure, but that looks like one of those attributes the QA team appends to certain elements they want to find with their automated browser tests. The whole purpose of those kinds of attributes is so the engineers won’t touch them and change their names, that way the automated tests can run for a long time without breaking. Again, I can’t make any guarantees, but this selector will probably be around for a while. So I felt pretty confident I could use that selector and not have it break in a short period of time due to twitter refactoring their DOM markup.

Once I had a selector I could use, I opened my text editor and created the following CSS file:

From there, I saved the .css file in my Dropbox folder (for backup purposes, i.e. a lazy man’s version control) then opened Safari’s preferences and selected my newly created file. A restart of Safari and boom! The sidebar was gone.

Feeling emboldened and empowered with my CSS sword of righteousness, I figured I’d go ahead and get rid of the DM/chat widget thing twitter recently introduced. It was merely visual noise to me. And fortunately, it had a similar way to be targeted: [data-testid="DMDrawer"] .

Screenshot of twitter.com in Safari with the developer tools open and targeting a parent DOM node of the right sidebar.

Pretty cool. Now I have a version of twitter custom tailored to me, free of a lot of distractions I don’t want to see.

Screenshot of twitter.com in Safari with a custom style sheet applied that hides the sidebar and the DM widget in the bottom right.

Observations Nobody Asked For

If you write a lot of custom styles for sites across the web, you could start running into naming collisions. It would be neat if you could scope styles to a specific domain. Maybe there’s a way to do it? I couldn’t think of one. Imagine:

JavaScript has access to a page’s URL via window.location but AFAIK that’s not available—at least not in any standardized way—in CSS.

It's likely a terrible idea, but we have custom user style sheets, is there such a thing as a custom user scripts? Imagine giving a .js file to the browser and it runs it on every single page, like a custom style sheet. Why? Because I want to specify all my custom styles using JavaScript not CSS.

Just kidding.

But seriously, if there was something like this, I could have a script that runs on every page and sticks an attribute on the root html element with the page’s URL. Imagine:

This would result in every page getting an attribute on the root element with the current page’s href on it.

This would allow me to scope every single one of my custom style sheet selectors to a specific domain:

Honestly, that sounds cool but impractical (not to mention the incredible security implications). It’s fun to think about though.

But hey, if I felt like disabling JavaScript, I could use this theoretical custom script functionality to run the following JavaScript on ever page I visit, just to show who really is in power:

I love old-school browser functionality like this. Can you imagine a feature like custom style sheets being proposed and implemented in today’s world? I feel like this is in Safari as a holdover from a bygone era. Could it ever get the momentum to happen today? I worry Apple might take it out sometime in the future.

All that said, if you want to read more, this post has a perspective on the history of custom style sheets in Safari that you might find interesting.

Update: 2020-01-14

I received an email from John P. Rouillard who read my question about having custom user scripts and said “You mean like greasemonkey or tapermonkey?”

I realized when I wrote that paragraph that I was merely describing what browser extensions are for. What I was trying to get at is that it would be really cool if custom user scripts were a feature of the browser, i.e. adding a custom user script was as simple as adding a custom style sheet: select a .js file on disk and boom, you’re done.

That said, maybe I’ll give one of these user scripts extensions a try. I’ve heard of greasemonkey and used it back in like 2012. But I’ve never heard of tampermonkey. Looks like it’s open source and even available for Safari . Thanks John!

  • Rachel Andrew
  • Feb 4, 2019

A Guide To CSS Support In Browsers

  • 15 min read
  • CSS Grid , CSS , Browsers
  • Share on Twitter ,  LinkedIn

About The Author

Rachel Andrew is a web developer, writer and speaker. She is the author of a number of books, including The New CSS Layout . She is one of the people behind the … More about Rachel ↬

Email Newsletter

Weekly tips on front-end & UX . Trusted by 200,000+ folks.

We will never live in a world where everyone viewing our sites has an identical browser and browser version, just as we will never live in a world where everyone has the same size screen and resolution. This means that dealing with old browsers — or browsers which do not support something that we want to use — is part of the job of a web developer. That said, things are far better now than in the past, and in this article, I’m going to have a look at the different types of browser support issues we might run into. I’m going to show you some ways to deal with them, and also look at things which might be coming soon which can help.

Why Do We Have These Differences?

Even in a world where the majority of browsers are Chromium-based, those browsers are not all running the same version of Chromium as Google Chrome. This means that a Chromium-based browser such as Vivaldi, might be a few versions behind Google Chrome.

And, of course, users do not always quickly update their browsers, although that situation has improved in recent years with most browsers silently upgrading themselves.

There is also the manner in which new features get into browsers in the first place. It is not the case that new features for CSS are designed by the CSS Working Group, and a complete spec handed down to browser vendors with an instruction to implement it. Quite often it is only when an experimental implementation happens, that all the finer details of the specification can be worked out. Therefore, feature development is an iterative process and requires that browsers implement these specifications in development. While implementation happens these days most often behind a flag in the browser or available only in a Nightly or preview version, once a browser has a complete feature, it is likely to switch it on for everyone even if no other browser yet has support.

All this means that — as much as we might like it — we will never exist in a world where features are magically available on every desktop and phone simultaneously. If you are a professional web developer then your job is to deal with that fact.

Bugs Vs. Lack Of Support

There are three issues that we face with regard to browser support:

  • No Support Of A Feature The first issue (and easiest to deal with) is when a browser does not support the feature at all.
  • Dealing With Browser “Bugs” The second is when the browser claims to support the feature, but does so in a way that is different to the way that other browsers support the feature. Such an issue is what we tend to refer to as a “browser bug” because the end result is inconsistent behavior.
  • Partial Support Of CSS Properties This one is becoming more common; a situation in which a browser supports a feature — but only in one context.

It’s helpful to understand what you are dealing with when you see a difference between browsers, so let’s have a look at each of these issues in turn.

1. No Support Of A Feature

If you use a CSS property or value that a browser does not understand, the browser will ignore it. This is the same whether you use a feature that is unsupported, or make up a feature and try to use it. If the browser does not understand that line of CSS, it just skips it and gets on with the next thing it does understand.

This design principle of CSS means that you can cheerfully use new features, in the knowledge that nothing bad will happen to a browser that doesn’t have support. For some CSS, used purely as an enhancement, that is all you need to do. Use the feature, make sure that when that feature is not available the experience is still good, and that’s it. This approach is the basic idea behind progressive enhancement, using this feature of the platform which enables the safe use of new things in browsers which don’t understand them.

If you want to check whether a feature you are using is supported by browsers then you can look at the Can I Use website. Another good place to look for fine-grained support information is the page for each CSS property on MDN . The browser support data there tends to be very detailed.

New CSS Understands Old CSS

As new CSS features are developed, care is taken in terms of how they interact with existing CSS. For example, in the Grid and Flexbox specification, it is detailed in terms of how display: grid and display: flex deal with scenarios such as when a floated item becomes a grid item, or a multicol container is turned into a grid. This means that certain behaviors are ignored, helping you to simply overwrite the CSS for the nonsupporting browser. These overrides are detailed in the page for Progressive enhancement and Grid Layout on MDN .

Detecting Support With Feature Queries

The above method only works if the CSS you need to use does not need other properties to go along with it. You might need to add additional properties to your CSS for older browsers which would then also be interpreted by the browsers which support the feature too.

A good example of this can be found when using Grid Layout. While a floated item which becomes a grid item loses all float behavior, it is likely that if you are trying to create a fallback for a grid layout with float, you will have added percentage widths and possibly margins to the items.

These widths and margins will then still apply when the floated item is a grid item. The width becomes a percentage of the grid track rather than the full width of the container; any margin will then be applied as well as a gap you may have specified.

Thankfully, there is a feature built into CSS and implemented into modern browsers which helps us deal with this situation. Feature Queries allow us to directly ask the browser what they support and then act on the response. Just like a Media Query — which tests for some properties of the device or screen — Feature Queries test for support of a CSS property and value.

Test For Support

Testing for support is the simplest case, we use @supports and then test for a CSS property and value. The content inside the Feature Query will only run if the browser responds with true, i.e. it does support the feature.

Test For No Support

You can ask the browser if it does not support a feature. In this case, the code inside the Feature Query will only run if the browser indicates it has no support.

Test For Multiple Things

If you need more than one property to be supported, use and .

If you need support of one property or another, use or .

Picking A Property And Value To Test For

You don’t need to test for every property you want to use — just something which would indicate support for the features you are planning to use. Therefore, if you want to use Grid Layout, you might test for display: grid . In the future (and once subgrid support lands in browsers), you might need to be more specific and test for subgrid functionality. In that case, you would test for grid-template-columns: subgrid to get a true response from only those browsers which had implemented subgrid support.

If we now return to our floated fallback example, we can see how feature queries will sort it out for us. What we need to do is to query the browser to find out if it supports grid layout. If it does, we can set the width on the item back to auto and the margin to 0 .

See the Pen Feature Queries and Grid by ( Rachel Andrew ) on CodePen .

Note that while I have included all of the grid code inside my feature query, I don’t need to. If a browser didn’t understand the grid properties it would ignore them so they could safely be outside of the feature query. The things that must be inside a feature query in this example are the margin and width properties, as these are needed for the old browser code but would also be applied by supporting browsers.

Embrace The Cascade

A very simple way to offer fallbacks is to utilize the fact that browsers ignore CSS that they don’t understand, and the fact that where everything else has equal specificity, source order is taken into account in terms of which CSS is applied to an element.

You first write your CSS for browsers which do not support the feature. Then test for support of property you want to use, if the browser confirms it has support overwrite the fallback code with your new code.

This is pretty much the same procedure that you might use when using media queries for responsive design, following a mobile-first approach. In that approach, you start with your layout for smaller screens, then add or overwrite things for larger ones as you move up through your breakpoints.

Can I Use CSS Feature Queries? Data on support for CSS Feature Queries across the major browsers from caniuse.com.

The above way of working means that you do not need to worry about browsers which do not support Feature Queries. As you can see from Can I Use , Feature Queries have really great support. The standout browsers that do not support them being any version of Internet Explorer.

It is likely, however, that the new feature you want to use is also not supported in IE. So, at the present time you will almost always start by writing CSS for browsers without support, then you test with a Feature Query. This Feature Query should test for support.

  • Browsers which support Feature Queries will return true if they have support and so the code inside the query will be used, overwriting the code for older browsers.
  • If the browser supports Feature Queries but not the feature being tested, it will return false. The code inside the feature query will be ignored.
  • If the browser does not support Feature Queries then everything inside the Feature Query block will be ignored, which means that a browser such as IE11 will use your old browser code, which is very likely exactly what you want!

2. Dealing With Browser “Bugs”

The second browser support issue is thankfully becoming less common. If you read “ What We Wished For ” (published at the end of last year), you can get a little tour into some of the more baffling browser bugs of the past. That said, any software is liable to have bugs, browsers are no exception. And, if we add to that the fact that due to the circular nature of specification implementation, sometimes a browser implemented something and then the spec changed so they now need to issue an update. Until that update ships, we might be in a situation where browsers do something different to each other.

Feature Queries can’t help us if the browser reports support of something supports it badly. There is no mode by which the browser can say, “ Yes, but you probably won’t like it .” When an actual interoperability bug shows up, it is in these situations where you might need to be a little more creative.

If you think you are seeing a bug then the first thing to do is confirm that. Sometimes when we think we see buggy behavior, and browsers doing different things, the fault lies with us. Perhaps we have used some invalid syntax, or are trying to style malformed HTML. In those cases, the browser will try to do something; however, because you aren’t using the languages as they were designed, each browser might cope in a different way. A quick check that your HTML and CSS is valid is an excellent first step.

At that point, I’d probably do a quick search and see if my issue was already widely understood. There are some repos of known issues, e.g. Flexbugs and Gridbugs . However, even just a well-chosen few keywords can turn up Stack Overflow posts or articles that cover the subject and may hand you a workaround.

But let’s say you don’t really know what is causing the bug, which makes it pretty hard to search for a solution. So, the next step is to create a reduced test case of your issue, i.e. stripping out anything irrelevant to help you identify exactly what triggers the bug. If you think you have a CSS bug, can you remove any JavaScript, or recreate the same styling outside of a framework? I often use CodePen to pop together a reduced test case of something I am seeing; this has the added advantage of giving me the code in a way I can easily share with someone else if I need to ask about it.

Most of the time, once you have isolated the issue, it is possible to think up an alternate way of achieving your desired result. You will find that someone else has come up with a cunning workaround, or you can post somewhere to ask for suggestions.

With that said, if you think you have a browser bug and can’t find anyone else talking about the same issue, it is quite possible you have found something new that should be reported. With all of the new CSS that has landed recently, issues can sometimes show up as people start to use things in combination with other parts of CSS.

Check out this post from Lea Verou about reporting such issues, “ Help The Community! Report Browser Bugs! ”. The article also has great tips for creating a reduced test case.

3. Partial Support Of CSS Properties

The third type of issue has become more common due to the way that modern CSS specifications are designed. If we think about Grid Layout and Flexbox, these specs both use the properties and values in Box Alignment Level 3, to do alignment. Therefore, properties such as align-items , justify-content , and column-gap are specified to be used in both Grid and Flexbox as well as other layout methods.

At the time of writing, however, the gap properties work in Grid Layout in all grid-supporting browsers, and column-gap works in Multicol; however, only Firefox has implemented these properties for Flexbox.

If I were to use margins to create a fallback for Flexbox, then test for column-gap and remove the margins, my boxes will have no space between them in browsers which support column-gap in Grid or multicol, so my fallback spacing will be removed.

This is a current limitation of Feature Queries. We don’t have a way to test for support of a feature in another feature. In the above situation, what I want to ask the browser is, “Do you have support for column-gap in Flexbox?” This way, I can get a negative response so I can use my fallback.

There is a similar issue with the CSS fragmentation properties break-before , break-after , and break-inside . As these have better support when the page is printed, browsers will often claim support. However, if you are testing for support in multicol, you get what appear to be false positives. I’ve raised an issue over at the CSS Working Group for this issue , however, it isn’t a straightforward problem to solve. If you have thoughts, please do add them there.

Testing For Selector Support

Currently, Feature Queries can only test for CSS Properties and Values. Another thing we might like to test for is the support of newer selectors, such as those in Level 4 of the Selectors specification. There is an explainer note and also an implementation behind a flag in Firefox Nightly of a new feature for Feature Queries which will achieve this.

If you visit about:config in Firefox and enable the flag layout.css.supports-selector.enabled then you can test to see if various selectors are supported. The syntax is currently very straightforward, for example to test for the :has selector:

This is a specification in development, however, you can see how features to help us manage the ever-present issues of browser support are being added as we speak.

Other Resources

It can seem frustrating when you want to use a feature and discover that it isn’t supported by one major browser, or if things seem to be behaving in different ways. I’ve rounded up some practical further reading that might help.

  • “ Using CSS Grid: Supporting Browsers Without Grid ” Options for dealing with older browsers and CSS Grid
  • “ Feature Queries ” MDN reference page for Feature Queries
  • “ CSS Grid And Progressive Enhancement ” MDN guide to Grid progressive enhancement
  • “ Backwards Compatibility Of Flexbox ” MDN guide to Flexbox support including details of older prefixed implementations
  • “ Pattern Library First ” How to manage fallback code using a pattern library

Further Reading

  • 55 Free High Quality Icon Sets
  • The Ultimate Guide To Cloning In Photoshop
  • Hand-Sketching: Things You Didn’t Know Your Doodles Could Accomplish
  • Switching From Adobe Fireworks To Sketch: Ten Tips And Tricks

Smashing Newsletter

Tips on front-end & UX, delivered weekly in your inbox. Just the things you can actually use.

Front-End & UX Workshops, Online

With practical takeaways, live sessions, video recordings and a friendly Q&A.

TypeScript in 50 Lessons

Everything TypeScript, with code walkthroughs and examples. And other printed books.

DEV Community

DEV Community

Stephan Lamoureux

Posted on Apr 23, 2021 • Updated on Oct 10, 2022

How to Target Specific Browsers With CSS

Web browsers are built with different rendering engines, and this causes small differences in the way your website appears between browsers. The sizing may be a little different, the colors aren't consistent, and many more things of that nature.

To counter this, we can use the following CSS to target and style specific browsers.

Chrome & Safari (Webkit)

Microsoft edge, ie11 and up, top comments (0).

pic

Templates let you quickly answer FAQs or store snippets for re-use.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

mikeyoung44 profile image

BRIGHT: New Text Retrieval Benchmark Requiring Intensive Reasoning to Identify Relevant Documents

Mike Young - Jul 21

jenesh profile image

How to Delete Files and Directories in Mac Terminal

Jenesh Napit - Aug 13

servbay profile image

Announcing ServBay 1.3.9: More Features, Smoother Experience! 🚀

ServBay - Jul 24

keploy profile image

Demystifying the Software Development Life Cycle (SDLC)

keploy - Aug 12

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free

-webkit-transition

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

Non-standard: This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

Note: All browsers support the transition property without vendor prefixes. Only WebKit (Safari), and not Chromium, based browsers support the -webkit-transition media feature. No browsers support transition without the prefix as a media query (though some browsers do support - -webkit-transform-3d ). Use the @supports (transition) feature query instead.

The -webkit-transition Boolean non-standard CSS media feature is a WebKit extension whose value is true if the browsing context supports CSS transitions .

Apple has a description in Safari CSS Reference ; this is now called transition there.

Note: You should not use this media feature; it was never specified, has never been widely implemented, and has been removed from most browsers . Use a @supports feature query instead.

Use @supports instead

Do not use the -webkit-transition media feature. Instead, test for transition support using the CSS @supports at-rule , like this:

Obsolete example

Before this became obsolete, you could use -webkit-transition in your CSS like this:

Specifications

Not part of any standard.

Browser compatibility

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

  • -webkit-transform-3d
  • -webkit-transform-2d
  • -webkit-animation
  • Test page at quirksmode.org
  • transition and using CSS transitions
  • @media and Using media queries
  • @supports and using feature queries

@supports selector()

Avatar of Chris Coyier

DigitalOcean provides cloud products for every stage of your journey. Get started with $200 in free credit!

I didn’t realize the support for @supports determining selector support was so good ! I usually think of @supports as a way to test for property: value pair support. But with the selector() function, we can test for selector support as well. It looks like this:

You just drop the selector right between the parens and that’s what it tests for.

That selector above is a pretty good test, actually. It’s a “selector list argument” that works for the :nth-child ‘n’ friends selectors. As I write, it’s only supported in Safari.

So let’s say your ideal situation is that the browser supports this selector. Here’s an example. You know that with <ol> and <ul> the only valid child element is <li> . But also say this list needs separators, so you (and I’m not saying this is a great idea) did this kind of thing:

Then you also want to zebra-stripe the list. And, if you want zebra striping, you need to select every other .list-item , ignoring the .separator . So…

But only Safari supports that… so you can do:

If you didn’t care what the fallback was, you wouldn’t even have to bother with the @supports at all. But say you do care about the fallback. Perhaps in the supported situation, the zebra striping does the heavy lifting of the UX you are shooting for, so all you need for the seperator is a bit of space. But for non-supporting browsers, you’ll need something beefier because you don’t have the zebra striping.

So now you can style both situations:

If we get the @when syntax, then we can write it a little cleaner:

Anyway. The end result is…

only safari browser support css

There is a JavaScript API for testing support as well. I wasn’t sure if this would actually work, but it appears to! This fails in Chrome and passes in Safari as I write:

While I was putting this together, I was thinking… hmmmmmmm — what CSS selectors are out there that have weird cross-browser support? It’s really not that many. And even of those that do have weird cross-browser support, thinking of the number of use-cases where you care to actually wrap it in an @supports (rather than just let it fail) is fairly few.

The ::marker pseudo-element would have been a great one, but it’s pretty well supported now. I was thinking the case-insensitive attribute selector, like [href$="pdf" i] , would have been a good one, but nope, also well supported. Same deal with the comma-separated :not(a, .b, [c]) . Maybe something like :fullscreen / :-webkit-full-screen would be interesting and useful because it’s uniquely not supported in iOS Safari?

What is the ‘i’ at the end of this: [href$=”pdf” i]

Never mind: [attr operator value i] Adding an i (or I) before the closing bracket causes the value to be compared case-insensitively (for characters within the ASCII range).

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

Copy and paste this code: micuno *

Leave this field empty

COMMENTS

  1. css

    The coming versions of Firefox and Microsoft Edge have added support for multiple -webkit- CSS codes in their programming, and both Edge and Safari 9 have added support for @supports feature detection. Chrome and Firefox included @supports previously. /* Chrome 28+, Now Also Safari 9+, Firefox, and Microsoft Edge */.

  2. Applying CSS Styles to Safari Browser Only

    CSS feature queries allow you to conditionally apply styles based on a browser's capability support. We can leverage @supports to target Safari like so: .myElement {. /* Safari only CSS */. This will restrict the CSS rules to only apply in browsers that recognize the -webkit-appearance property.

  3. How to Create Browser Specific CSS Code

    When it comes to the Microsoft Edge browser, the process is simple as it involves a simple selector that has a property value. It also provides automatic alignment, which is considered the easy way to create browser-specific CSS code. @supports (-ms-ime-align:auto) {. selector { property: value; } }

  4. Apply CSS only for Safari?

    0. Using the UserAgent string, you can check for Safari and !Chrome. Both use the WebKit Renderer and both have Safari in the UA string, but Chrome also has 'Chrome'. To be honest, I'd just check for Webkit and code to that because who knows what other WebKit browser put in their UA strings. Safari : Mozilla/5.0 (Windows; U; Windows NT 6.1; zh ...

  5. CSS @ supports rules to target only Firefox / Safari / Chromium

    As Chromium (Blink) currently is the only browser that supports @property, we need to create a @supports rule that targets Chromium only. While at it let's also create @supports rules to target only Safari (WebKit), Firefox (Gecko), or a combination thereof. Looking at what each browser uniquely supports, these three rules can be used as a ...

  6. How to Fix CSS Issues on Safari

    Displaying properties in Safari. There is a CSS appearance property used to display an element using a platform-native styling based on the users' operating system's theme. To make it work on Safari, we must set the appearance property to its "none" value. Also, use -WebKit- and -Moz- vendor prefixes. Let's see an example, where we use this ...

  7. FabioRosado

    After testing different things and playing around with the media query, I've come to the final solution. I've also added a rule to trigger the CSS only when the screen is smaller than 900px high, because we don't want the menu to be broken on a larger screen. css. Copy. 1@medianot all and(max-height:899px)and(min-resolution:.1dpi){.

  8. CSS Reference Browser Support

    The table below lists all CSS properties and how each property is supported in the different browsers: The number to the right of the browser icon indicates in which browser version the property was first supported. Property. Edge. Firefox. Chrome. Safari.

  9. Custom Style Sheets in Safari

    First off, Safari lets you specify a custom style sheet. In case you don't know, a custom style sheet is a bunch of CSS rules that you get to specify and then the browser will apply them to every single web page you visit. The first thing I needed to do was open twitter.com and find out what type of CSS rule I could write to target that right ...

  10. A Guide To CSS Support In Browsers

    Dealing with old browsers — or browsers which do not support something that we want to use — is part of the job of a web developer. That said, things are far better now than in the past. In this article, Rachel Andrew details the different types of browser support issues, and shows how CSS is evolving to make it easier to deal with them.

  11. Detect Safari browser with pure CSS

    To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-or -moz-. We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).

  12. How to Craft Browser Specific CSS Code

    Source. To write browser-specific CSS code in Google Chrome, you can follow these browser-specific CSS properties: To target the support of browser-specific CSS properties on the Webkit browsers (including Safari) for all Chrome versions: .selector:not(*:root) { property:value; } To target the support of properties on Chrome versions >= 29:

  13. @supports

    The @supports CSS at-rule lets you specify CSS declarations that depend on a browser's support for CSS features. Using this at-rule is commonly called a feature query. ... It returns true only if both of the shorter expressions are also true. The following example returns true if and only if the two shorter expressions are simultaneously true:

  14. -webkit-prefixed CSS extensions

    Use the CSS multicolumn layout with the standard break-inside property instead. -webkit-font-feature-settings. Use the font-feature-settings property instead. -webkit-hyphenate-character. Use the standard hyphenate-character property instead. -webkit-initial-letter. Use the standard initial-letter property instead.

  15. How to Target Specific Browsers With CSS

    Web browsers are built with different rendering engines, and this causes small differences in the way your website appears between browsers. The sizing may be a little different, the colors aren't consistent, and many more things of that nature. To counter this, we can use the following CSS to target and style specific browsers.

  16. 3 CSS techniques to improve Browser Compatibility

    Table of Contents. 3 CSS techniques for Improved Cross Browser Compatibility. 1. Setting gradient color on div in different browsers. 2. Setting border-radius in Popular Browsers (Mozilla, Chrome, Safari, Opera) 3. Setting background image for select tags in Chrome. Commonly Observed Cross-Browser Compatibility Issues.

  17. -webkit-transition

    Note: All browsers support the transition property without vendor prefixes. Only WebKit (Safari), and not Chromium, based browsers support the -webkit-transition media feature. No browsers support transition without the prefix as a media query (though some browsers do support - -webkit-transform-3d).Use the @supports (transition) feature query instead.

  18. WebKit Features In Safari 16.0

    Source: WebKit.org. Just gonna drop in the new CSS features from the release notes: Added size queries support for Container Queries. Chrome started supporting it in Version 105, so all we need is Firefox to join the party to get The Big Three™ covered. Added support for Container Query Units. These units go hand-in-hand with Container Queries.

  19. css

    Closed 6 years ago. I simply wants to modify a styling property for safari browsers only, which will override the default property. simple example: Default. color: blue; Safari browsers. color: red; I imagine this can be done with the @include function of scss but I am not sure how.

  20. @supports Selector()

    It looks like this: @supports selector(:nth-child(1 of .foo)) { } You just drop the selector right between the parens and that's what it tests for. That selector above is a pretty good test, actually. It's a "selector list argument" that works for the :nth-child 'n' friends selectors. As I write, it's only supported in Safari.

  21. How to apply specific CSS rules to Chrome only?

    The accepted answer matches Firefox 80+ also. To target all Webkit browsers (Edge 79+, Chrome, Safari), find a -webkit specific CSS extension that is not supported by Firefox (use https://caniuse.com).This is a moving target; one of the Webkit browsers may remove it, and a non-Webkit browser may add support for it.