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

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 .

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

pexlkeys profile image

Pexl Keys - How to Upgrade Microsoft Office 2019 to 2021

Pexl Keys - Jul 16

javafullstackdev profile image

Breaking Down the Differences Between SOAP and REST

JavaFullStackDev.in - Jul 16

dev_habib_nuhu profile image

Monolithic vs Microservice Architecture: A Beginner's Guide

Habib Nuhu - Jul 15

scofieldidehen profile image

Adding a User-Controlled Camera Feature To Our Python GUI Clock

Scofield Idehen - Jul 15

DEV Community

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

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!

CSS rule to style Safari 16.x only

Hello everyone

I was wondering if someone already figured out the CSS rules to only style Safari 16 on MacOS. Since the update some of my stylings break (thanks apple dev team) and I really need to fix them as soon as possible. This rule:

@ media not all and (min-resolution:.001dpcm) { @ supports (-webkit-appearance:none) and (display:flow-root) { .selector { property:value; } } }

will not work

kind regards

apply css only for safari

It works in iOS16 down to iOS 10:

@ supports (-webkit-hyphens:none){ @ content }

Hi team, Any other -webkit to use ??

wouldnt work. Thanks

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

Instantly share code, notes, and snippets.

@jbutko

jbutko / style.css

  • Download ZIP
  • Star ( 9 ) 9 You must be signed in to star a gist
  • Fork ( 1 ) 1 You must be signed in to fork a gist
  • Embed Embed this gist in your website.
  • Share Copy sharable link for this gist.
  • Clone via HTTPS Clone using the web URL.
  • Learn more about clone URLs
  • Save jbutko/6718701 to your computer and use it in GitHub Desktop.

@frknbasaran

frknbasaran commented Nov 25, 2019

@ntnbst thanks a lot. <3

Sorry, something went wrong.

@carlbrn

carlbrn commented Dec 10, 2019

@ntnbst so many thanks!

@AnithaPal

AnithaPal commented Jan 2, 2020

@Valeka , Thanks It works perfectly.

@rhostem

rhostem commented Feb 27, 2020

@ntnbt thanks a lot!!

@vihuy

vihuy commented Apr 21, 2020

when i added @media screen and (min-color-index: 0) and (-webkit-min-device-pixel-ratio: 0) { @media { #activity-list{ margin-top: 25px; } }} it still runs on chrome browser

@Hungreeee

Hungreeee commented Apr 26, 2020

thank @ntnbt a lot it worked well for me.

@vihuy I only do: .classname { @media screen and (min-color-index: 0) and (-webkit-min-device-pixel-ratio: 0) { @media { margin-top: 25px; } } }

or if u are using React MUI useStyles like me just ' @media not all and (min-resolution:.001dpcm)': { ' @supports (-webkit-appearance:none)': { sth here }, },

vihuy commented May 8, 2020

@MynameisHung thank you.

@JonathanFSilva

JonathanFSilva commented Aug 12, 2020

Thanks @ntnbst , your approach worked for me!

@onenazmul

onenazmul commented Aug 29, 2020

It worked, thanks a lot @ntnbst

@yogesh-xseed

yogesh-xseed commented Nov 3, 2020 • edited Loading

@media screen and (-webkit-min-device-pixel-ratio: 0) { _::-webkit-full-page-media, _:future, :root , .some-class { top:just save 0; } }

@Valeka thank you so much you just saved my day.

@sanket4real

sanket4real commented Jan 18, 2021

Thanks @ntnbst , it worked

@xoriant-vikas

xoriant-vikas commented Feb 18, 2021

@media not all and (min-resolution:.001dpcm) { @supports (-webkit-appearance:none) { .safari_only { color:#0000FF; background-color:#CCCCCC; } }}

although its working perfectly but have sass lint error.

Include leading zeros on numbers for @media not all and (min-resolution:.001dpcm)
Vendor prefixes should not be used for @supports (-webkit-appearance:none)

@Chelny

Chelny commented Mar 21, 2021

Thanks @ntnbst !

@Muhammad-Naiem

Muhammad-Naiem commented Mar 24, 2021

need just ios chorme browser all media

@nguyen422

nguyen422 commented May 7, 2021

@ntnbst works for me too ;) Thanks so much!!

@ShiBa-Shin

ShiBa-Shin commented Sep 1, 2021

@ntnbst Works like a charm. Thanks for shared this.

@Mil00Z

Mil00Z commented Oct 4, 2021

@ntnbst OMG , i don't really understand it works but thank you very much !!!! (if you have some explanations, i'm ready ^^)

@shivam2112

shivam2112 commented Dec 1, 2021

works fine on Chrome and Firefox but not on Safari (iOS or MacOS). I am getting a “zero sized error” on Safari. I recently had an expired cert but renewed it using Let’s Encrypt. I did not test on Safari after renewal as it worked fine on Chrome. created wordpress website can solve this problem. Thanks in advance!

Mil00Z commented Dec 5, 2021

It's work without SASS process The hack applies on Firefox Standard (why ? Don't know) I think some of User Agent specs are the same between Firefox and Safari MacOs

@4leeX

4leeX commented Aug 12, 2022

@ntnbst thanks man

@EngineerPlug

EngineerPlug commented Oct 28, 2022

So can i just plug this in and it will work?

Mil00Z commented Oct 31, 2022

yes, it's work for me so just check the Developer tools on Firefox so the hack appear on sometimes :)

@dkoutevska

dkoutevska commented Nov 9, 2022

FYI: @ntnbst 's approach works great for desktop browsers, but it will target every mobile browser on iOS devices . :)

@tettoffensive

tettoffensive commented Feb 2, 2023

@ntnbst 's approach did not work for me on Safari desktop. It didn't affect any browser. If I remove the "not all", it seems to affect all browsers.

@cynthiaeddy

cynthiaeddy commented Oct 9, 2023

@Valeka - many thanks! your solution worked for me.

@MakerTim

MakerTim commented Mar 7, 2024

Works fine for me & without errors from linter(s)

@CerealKiller97

CerealKiller97 commented Mar 31, 2024

@MakerTim Thank you so much!!! You made my day!!

@RobinSen2217

RobinSen2217 commented Apr 23, 2024

@MakerTim Thank you very much, good sir!!!

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Safari 5 extension for site-specific CSS customisation?

Is there a Safari 5 extension along the lines of Stylish ? Basically a way to quickly install or create site-specific CSS files.

  • browser-addons

dbr's user avatar

3 Answers 3

Feel free to install my Stylish extension for Safari (also available in Apple Extensions gallery, Developer section) or fork my project on GitHub .

Extension in development, but you can create new styles, search/manage/edit styles from user styles.org database, styles options - only default values supported in current version.

Dave's user avatar

  • What's the status of this? The extensions gallery has been replaced by the app store, and I can't find it there. –  Elliott B Commented Aug 25, 2018 at 5:02
  • 1 Unfortunatelly Apple turned Stylish Safari extension off. By any chance, can someone tell me where my custom CSS were stored by it while I was using it? Had a lot off custom CSS that I really would like to get back. –  Marcelo Myara Commented Apr 15, 2019 at 22:14

http://code.grid.in.th/

Thanks to http://safariextensions.tumblr.com/post/687054388/post-user-css-06-11-10

bradx3's user avatar

It appears as though an independent developer has ported or rewritten Stylish as a Safari extension ! It is currently in beta according to the developer.

NReilingh's user avatar

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged safari css browser-addons ..

  • Featured on Meta
  • Announcing a change to the data-dump process
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...

Hot Network Questions

  • Small-ish (sub-centimeter) latching/locking connector for multiple (~4) isolated wires not bundled into the same plug
  • When we say "roll out" a product, do we mean like a carpet or like a car?
  • Examples of the most subordinate infinitive clauses combined in one sentence
  • Why were the names of Western Roman emperors mostly unique?
  • Why doesn't "I never found the right one" use the present perfect?
  • What can a time traveler use to generate an encryption key to encrypt information so it's only decryptable after a given time period
  • Display attribute table with specified decimals
  • Publishing a paper written in your free time as an unaffiliated author when you are affiliated
  • Is there a way to render someone braindead while leaving the organs and body fully intact?
  • The vertiginous question: Why am I me and not someone else?
  • Translation closest to original Heraclitus quote "no man steps in the same river twice, for it is not the same river and he is not the same man"
  • When labeling, "Wrap on character" drops the wrap character
  • What are the safe assumptions I can make when installing a wall oven without model/serial?
  • In this position, why is the move 12. Be3 rarely played by top players?
  • Explain This Star Battle Clue
  • What are applicable skills and abilities for dealing with paperwork, administration and law in 5e?
  • What is a Cheese Dip (as made by Henri Willig)?
  • Former manager and team keep reaching out with questions despite transferring to a new team
  • A hat puzzle question—how to prove the standard solution is optimal?
  • Is "natural person" an idiomatic way to describe someone who's the opposite of pretentious?
  • Make both colors connected
  • Does this follow from Everett's Many-Worlds?
  • English equivalent for the idiom "mother-in-law has forgotten to wear her saree (dress)"
  • How to make an entire section as a conjecture?

apply css only for safari

  • Write for us
  • Advertising

Web Development, Networking, Security, SEO

CSS3 Media Query to target only Internet Explorer (from IE6 to IE11+), Firefox, Chrome, Safari and/or Edge A set of useful CSS3 media queries to target only specific versions of the various browsers: Internet Explorer, Mozilla Firefox, Google Chrome, Apple Safari and Microsoft Edge

CSS3 Media Query to target only Internet Explorer (from IE6 to IE11+), Firefox, Chrome, Safari and/or Edge

Table of Contents

IE 6, 7 and 8

Ie 8 standards mode only, ie 8,9 and 10, ie 9 and above, ie 9 and 10, ie 10 and above, ie 11 (and above..), microsoft edge, any version (gecko), quantum only (stylo), legacy (pre-stylo), chrome & safari (any version),  safari (7.1+), safari (from 6.1 to 10.0), safari (10.1+).

If you're a HTML developer you most likely know that there are times when you need to selectively apply some styles to a specific browser, or to a specific version/build of a browser. When such scenarios occur, there are a number of CSS and/or JS based techniques to achieve that result.

Here's a collection of media queries that will allow you to do that in pure CSS3 code, without a single line of JavaScript code: most of them come from the  browserhacks.com web site, which is an excellent resource of browser-specific CSS and JavaScript hacks for these kind of tasks.

Internet Explorer

For further info or additional media queries, visit the awesome browserhacks.com website!

Print Friendly, PDF & Email

Related Posts

TS2564 (TS) Property has no initializer TypeScript error in Visual Studio 2017 - How to fix

How to become a Web Developer: a detailed plan for learning JavaScript A list of the main study topics that await a novice JavaScript developer in his/her learning path to become a great web developer

May 19, 2020 May 19, 2020

Tabulazer - Chrome Extension to Filter and Sort HTML Tables

Tabulazer - Chrome Extension to Filter and Sort HTML Tables A free Google Chrome Extension that can be used to filter, sort and enlarge HTML tables from any web page

October 2, 2019

7 typical reasons why Bootstrap is ideal for responsive Web Design

7 typical reasons why Bootstrap is ideal for responsive Web Design A list of some great features that still makes Bootstrap the world’s most popular front-end component library

July 25, 2019 July 25, 2019

apply css only for safari

IT Project Manager, Web Interface Architect and Lead Developer for many high-traffic web sites & services hosted in Italy and Europe. Since 2010 it's also a lead designer for many App and games for Android, iOS and Windows Phone mobile devices for a number of italian companies. Microsoft MVP for Development Technologies since 2018.

6 Comments on “ CSS3 Media Query to target only Internet Explorer (from IE6 to IE11+), Firefox, Chrome, Safari and/or Edge A set of useful CSS3 media queries to target only specific versions of the various browsers: Internet Explorer, Mozilla Firefox, Google Chrome, Apple Safari and Microsoft Edge ”

Using a media query like this, @media screen and (-webkit-min-device-pixel-ratio:0) and (min-resolution:.001dpcm) {, to only target Chrome previously worked but now Firefox is picking up those styles in that media query. Any ideas for another workaround for just Chrome? Thanks!

Try one of these:

The css for ‘Safari (from 6.1 to 10.0)’ affects ALL browsers on iPad: Chrome, Safari, Opera. Not only Safari.

_:lang(x)::-ms-backdrop, .selector { color: blue; } /* IE11 */ _:-ms-lang(x)::backdrop, .selector { color: blue; } /* Edge */ _:lang(x)::-internal-media-controls-overlay-cast-button, .selector { color: blue; } /* Chrome */ _:lang(x)::x-, .selector { color: blue; } /* Safari */ _:-moz-any(x), .selector { color: blue; } /* Firefox */

not from me

sadly that edge things no longer works.. kind of tough to find an edge only query..

How to add a media query for a specific browser with specific width? for e.g. Safari browser version 10 and above with width: 1440px

Leave a Reply Cancel reply

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

 Aggiungi e-mail alla newsletter

Notify me of follow-up comments by email.

Notify me of new posts by email.

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

Css – Apply CSS only for Safari

Is it possible to add a block of css that I only want to be displayed in Safari and no other browsers?

Best Answer

Here's an example which would set the font colour of your site to green if your browser is Safari or Chrome (both share the common Webkit rendering engine).

This is taken from another post here

Related Solutions

Html – how to apply css to iframe.

Edit: This does not work cross domain unless the appropriate CORS header is set.

There are two different things here: the style of the iframe block and the style of the page embedded in the iframe. You can set the style of the iframe block the usual way:

The style of the page embedded in the iframe must be either set by including it in the child page:

Or it can be loaded from the parent page with Javascript:

Html – Set cellpadding and cellspacing in CSS

For controlling "cellpadding" in CSS, you can simply use padding on table cells. E.g. for 10px of "cellpadding":

For "cellspacing", you can apply the border-spacing CSS property to your table. E.g. for 10px of "cellspacing":

This property will even allow separate horizontal and vertical spacing, something you couldn't do with old-school "cellspacing".

Issues in IE ≤ 7

This will work in almost all popular browsers except for Internet Explorer up through Internet Explorer 7, where you're almost out of luck. I say "almost" because these browsers still support the border-collapse property, which merges the borders of adjoining table cells. If you're trying to eliminate cellspacing (that is, cellspacing="0" ) then border-collapse:collapse should have the same effect: no space between table cells. This support is buggy, though, as it does not override an existing cellspacing HTML attribute on the table element.

In short: for non-Internet Explorer 5-7 browsers, border-spacing handles you. For Internet Explorer, if your situation is just right (you want 0 cellspacing and your table doesn't have it defined already), you can use border-collapse:collapse .

Note: For a great overview of CSS properties that one can apply to tables and for which browsers, see this fantastic Quirksmode page .

Related Topic

  • Css – How to vertically center a “div” element for all browsers using CSS
  • Html – How to give text or an image a transparent background using CSS
  • Css – How to disable text selection highlighting
  • Css – CSS parent selector
  • Html – How to style a dropdown with only CSS
  • Html – Change a HTML5 input’s placeholder color with CSS
  • Css – Transitions on the CSS display property
  • Javascript – Is it possible to apply CSS to half of a character

Private Browsing 2.0

Jul 16, 2024

by John Wilander , Charlie Wolfe, Matthew Finkel, Wenson Hsieh, and Keith Holleman

When we invented Private Browsing back in 2005, our aim was to provide users with an easy way to keep their browsing private from anyone who shared the same device. We created a mode where users do not leave any local, persistent traces of their browsing. Eventually all other browsers shipped the same feature. At times, this is called “ephemeral browsing.”

We baked in cross-site tracking prevention in all Safari browsing through our cookie policy, starting with Safari 1.0 in 2003. And we’ve increased privacy protections incrementally over the last 20 years. (Learn more by reading Tracking Prevention in Webkit .) Other popular browsers have not been as quick to follow our lead in tracking prevention but there is progress.

Apple believes that users should not be tracked across the web without their knowledge or their consent. Entering Private Browsing is a strong signal that the user wants the best possible protection against privacy invasions, while still being able to enjoy and utilize the web. Staying with the 2005 definition of private mode as only being ephemeral, such as Chrome’s Incognito Mode , simply doesn’t cut it anymore. Users expect and deserve more.

So, we decided to take Private Browsing further and add even more protection beyond the normal Safari experience. Last September, we added a whole new level of privacy protections to Private Browsing in Safari 17.0. And we enhanced it even further in Safari 17.2 and Safari 17.5. Plus, when a user enables them, all of the new safeguards are available in regular Safari browsing too.

With this work we’ve enhanced web privacy immensely and hope to set a new industry standard for what Private Browsing should be.

Enhanced Private Browsing in a Nutshell

These are the protections and defenses added to Private Browsing in Safari 17.0:

Link Tracking Protection

  • Blocking network loads of known trackers, including CNAME-cloaked known trackers

Advanced Fingerprinting Protection

  • Extensions with website or history access are off by default

In addition, we added these protections and defenses in all browsing modes:

  • Capped lifetime of cookies set in responses from cloaked third-party IP addresses
  • Partitioned SessionStorage
  • Partitioned blob URLs (starting in Safari 17.2)

We also expanded Web AdAttributionKit (formerly Private Click Measurement) as a replacement for tracking parameters in URL to help developers understand the performance of their marketing campaigns even under Private Browsing.

Screenshot of Private Browsing in Safari

However, before we dive into these new and enhanced privacy protections, let’s first consider an important aspect of these changes: website compatibility risk.

The Risk of Breaking Websites and How We Mitigate It

There are many ideas for how to protect privacy on the web, but unfortunately many of them may break the user’s experience. Like security protections in real life, a balance must be struck. The new Private Browsing goes right up to the line, attempting to never break websites. But of course there is a risk that some parts of some sites won’t work. To solve this, we give users affordances to reduce privacy protections on a per-site basis. Such a change in privacy protections is only remembered while browsing within a site. This option is a last resort when a web page is not usable due to the privacy protections.

Reload menu with Reload Reducing Privacy Protections selected

All of the new privacy protections in Private Browsing are also available in regular browsing. On iOS, iPadOS and visionOS go to Settings > Apps > Safari > Advanced > Advanced Tracking and Fingerprinting Protection and enable “All Browsing”. On macOS go to Safari > Settings > Advanced and enable “Use advanced tracking and fingerprinting protection”:

Safari Advanced Settings with "Use advanced tracking and fingerprinting protection in all browsing" selected

Let’s now walk through how these enhancements work.

Safari’s Private Browsing implements two new protections against tracking information in the destination URL when the user navigates between different websites. The specific parts of the URL covered are query parameters and the fragment. The goal of these protections is to make it more difficult for third-party scripts running on the destination site to correlate user activity across websites by reading the URL.

Let’s consider an example where the user clicks a link on clickSource.example , which takes them to clickDestination.example. The URL looks like this:

Safari removes a subset of query parameters that have been identified as being used for pervasive cross-site tracking granular to users or clicks. This is done prior to navigation, such that these values are never propagated over the network. If known_tracking_param above represents such a query parameter, the URL that’s used for navigation will be:

As its name suggests, the campaign above represents a parameter that’s only used for campaign attribution, as opposed to click or user-level tracking. Safari allows such parameters to pass through.

Finally, on the destination site after a cross-site navigation, all third-party scripts that attempt to read the full URL (e.g. using location.search , location.href , or document.URL ) will get a version of the URL that has no query parameters or fragment. In our example, this script-exposed value is simply:

In a similar vein, Safari also hides cross-site any document.referrer from script access in Private Browsing.

Web AdAttributionKit in Private Browsing

Web AdAttributionKit (formerly Private Click Measurement) is a way for advertisers, websites, and apps to implement ad attribution and click measurement in a privacy-preserving way. You can read more about it here . Alongside the new suite of enhanced privacy protections in Private Browsing, Safari also brings a version of Web AdAttributionKit to Private Browsing. This allows click measurement and attribution to continue working in a privacy-preserving manner.

Web AdAttributionKit in Private Browsing works the same way as it does in normal browsing, but with some limits:

  • Attribution is scoped to individual Private Browsing tabs, and transfers attribution across new tabs opened when clicking on links. However, attribution is not preserved through other indirect means of navigation: for instance, copying a link and pasting in a new tab. In effect, this behaves similarly to how Web AdAttributionKit works for Direct Response Advertising .
  • Since Private Browsing doesn’t persist any data, pending attribution requests are discarded when the tab is closed.

Blocking Network Loads of Known Trackers

Safari 17.0 also comes with an automatically enabled content blocker in Private Browsing, which blocks network loads to known trackers. While Intelligent Tracking Prevention has long blocked all third party cookies, blocking trackers’ network requests from leaving the user’s device in the first place ensures that no personal information or tracking parameters are exfiltrated through the URL itself.

This automatically enabled content blocker is compiled using data from DuckDuckGo and from the EasyPrivacy filtering rules from EasyList. The requests flagged by this content blocker are only entries that are flagged as trackers by both DuckDuckGo and EasyPrivacy. In doing so, Safari intentionally allows most ads to continue loading even in Private Browsing.

Private Browsing also blocks cloaked network requests to known tracking domains. They otherwise have the ability to save third party cookies in a first-party context. This protection requires macOS Sonoma or iOS 17. By cloaked we mean subdomains mapped to a third-party server via CNAME cloaking or third-party IP address cloaking. See also the “Defending Against Cloaked First Party IP Addresses” section below.

When Safari blocks a network request to a known tracker, a console message of this form is logged, and can be viewed using Web Inspector:

Network Privacy Enhancements

Safari 15.0 started hiding IP addresses from known trackers by default. Private Browsing in Safari 17.0 adds the following protections for all users:

  • Encrypted DNS . DNS queries are used to resolve server hostnames into IP addresses, which is a necessary function of accessing the internet. However, DNS is traditionally unencrypted, and allows network operators to track user activity or redirect users to other servers. Private Browsing uses Oblivious DNS over HTTPS by default, which encrypts and proxies DNS queries to protect the privacy and integrity of these lookups.
  • Proxying unencrypted HTTP . Any unencrypted HTTP resources loaded in Private Browsing will use the same multi-hop proxy network used to hide IP addresses from trackers. This ensures that attackers in the local network cannot see or modify the content of Private Browsing traffic.

Additionally, for iCloud+ subscribers who have iCloud Private Relay turned on, Private Browsing takes privacy to the next level with these enhancements:

  • Separate sessions per tab . Every tab that the user opens in Private Browsing now uses a separate session to the iCloud Private Relay proxies. This means that web servers won’t be able to tell if two tabs originated on the same device. Each session is assigned egress IP addresses independently. Note that this doesn’t apply to parent-child windows that need a programmatic relationship, such as popups and their openers.
  • Geolocation privacy by default . Private Browsing uses an IP location based on your country and time zone, not a more specific location.
  • Warnings before revealing IP address . When accessing a server that is not accessible on the public internet, such as a local network server or an internal corporate server, Safari cannot use iCloud Private Relay. In Private Browsing, Safari now displays a warning requesting that the user consents to revealing their IP address to the server before loading the page.

Extensions in Private Browsing

Safari 17.0 also boosts the privacy of Extensions in Private Browsing. Extensions that can access website data and browsing history are now off by default in Private Browsing. Users can still choose to allow an extension to run in Private Browsing and gain all of the extension’s utility. Extensions that don’t access webpage contents or browsing history, like Content Blockers, are turned on by default in Private Browsing when turned on in Safari.

With Safari and subsequently other browsers restricting stateful tracking (e.g. cross-site cookies), many trackers have turned to stateless tracking, often referred to as fingerprinting .

Types of Fingerprinting

We distinguish these types of fingerprinting:

  • Device fingerprinting . This is about building a fingerprint based on device characteristics, including hardware and the current operating system and browser. It can also include connected peripherals if they are allowed to be detected. Such a fingerprint cannot be changed by the user through settings or web extensions.
  • Network and geographic position fingerprinting . This is about building a fingerprint based on how the device connects to the Internet and any means of detecting its geographic position. It could be done by measuring roundtrip speeds of network requests or simply using the IP address as an identifier.
  • User settings fingerprinting . This is about reading the state of user settings such as dark/light mode, locale, font size adjustments, and window size on platforms where the user can change it. It also includes detecting web extensions and accessibility tools. We find this kind of fingerprinting to be extra hurtful since it exploits how users customize their web experience to fit their needs.
  • User behavior fingerprinting . This is about detecting recurring patterns in how the user behaves. It could be how the mouse pointer is used, how quickly they type in form fields, or how they scroll.
  • User traits fingerprinting . This is about figuring out things about the user, such as their interests, age, health status, financial status, and educational background. Those gleaned traits can contribute to a unique ID but also can be used directly to target them with certain content, adjust prices, or tailor messages.

Fingerprint Stability

A challenge for any tracker trying to create a fingerprint is how stable the fingerprint will be over time. Software version fingerprinting changes with software updates, web extension fingerprinting changes with extension updates and enablement/disablement, user settings change when the user wants, multiple users of the same device means behavior fingerprints change, and roaming devices may change network and geographic position a lot.

Fingerprinting Privacy Problem 1: Cross-Site Tracking

Fingerprints can be used to track the user across websites. If successful, it defeats tracking preventions such as storage partitioning and link decoration filtering.

There are two types of solutions to this problem:

  • Make the fingerprint be shared among many users, so called herd immunity.
  • Make the fingerprint unique per website, typically achieved via randomized noise injection.

Fingerprinting Privacy Problem 2: Per-Site User Recall

Less talked about is the fingerprinting problem of per-site user recall. Web browsers offer at least two ways for the user to reset their relationship with a website: Clear website data or use Private Browsing. Both make a subsequent navigation to a website start out fresh.

But fingerprinting defeats this and allows a website to remember the user even though they’ve opted to clear website data or use Private Browsing.

  • Make the fingerprint unique per website, and generate a new unique fingerprint for every fresh start.

Fingerprinting Privacy Problem 3: Per-Site Visitor Uniqueness

The ultimate anti fingerprinting challenge in our view is to address a specific user’s uniqueness when visiting a specific website. Here’s a simple example:

Having the locale setting to US/EN for American English may provide ample herd immunity in many cases. But what happens when a user with that setting visits an Icelandic government website or a Korean reading club website? They may find themselves in a very small “herd” on that particular website and combined with just a few more fingerprinting touch points they can be uniquely identified.

Addressing per-site visitor uniqueness is not possible in general by a browser unless it knows what the spread of visitors looks like for individual websites.

Fingerprinting Protections at a High Level

We view cross-site tracking and per-site user recall as privacy problems to be addressed by browsers.

Our approach : Make the fingerprint unique per website, and generate a new unique fingerprint for every fresh start such as at website data removal.

Our tools :

  • Use multi-hop proxies to hide IP addresses and defend against network and geographic position fingerprinting.
  • Limit the number of fingerprintable web APIs whenever possible. This could mean altering the APIs, gating them behind user permissions, or not implementing them.
  • Inject small amounts of noise in return values of fingerprintable web APIs.

Fingerprinting Protection Details

Safari’s new advanced fingerprinting protections make it difficult for scripts to reliably extract high-entropy data through the use of several web APIs:

  • To make it more difficult to reliably extract details about the user’s configuration, Safari injects noise into various APIs: namely, during 2D canvas and WebGL readback, and when reading AudioBuffer samples using WebAudio.
  • To reduce the overall entropy exposed through other APIs, Safari also overrides the results of certain web APIs related to window or screen metrics to fixed values, such that fingerprinting scripts that call into these APIs for users with different screen or window configurations will get the same results, even if the users’ underlying configurations are different.

2D Canvas and WebGL

Many modern web browsers use a computer’s graphics processing unit (GPU) to accelerate rendering graphics. The Web’s Canvas API (2D Canvas) and WebGL API give a web page the tools it needs for rendering arbitrary images and complex scenes using the GPU, and analyzing the result. These APIs are valuable for the web platform, but they allow the web page to learn unique details about the underlying hardware without asking for consent. With Safari’s advanced fingerprinting protections enabled, Safari applies tiny amounts of noise to pixels on the canvas that have been painted using drawing commands. These modifications reduce the value of a fingerprint when using these APIs without significantly impacting the rendered graphics.

It’s important to emphasize that:

  • This noise injection only happens in regions of the canvas where drawing occurs.
  • The amount of noise injected is extremely small, and (mostly) should not result in observable differences or artifacts.

This strategy helps mitigate many of the compatibility issues that arise from this kind of noise injection, while still maintaining robust fingerprinting mitigations.

In Safari 17.5, we’ve bolstered these protections by additionally injecting noise when reading back data from offscreen canvas in both service workers and shared workers.

Similarly, when reading samples using the WebAudio API — via AudioBuffer.getChannelData() — a tiny amount of noise is applied to each sample to make it very difficult to reliably measure OS differences. In practice, these differences are already extremely minor. Typically due to slight differences in the order of operations when applying FFT or IFFT. As such, a relatively low amount of noise can make it substantially more difficult to obtain a stable fingerprint.

In Safari 17.5, we made audio noise injection more robust in the following ways:

  • The injected noise now applies consistently to the same values in a given audio buffer — this means a looping AudioSourceNode that contains a single high-entropy sample can’t be used to average out the injected noise and obtain the original value quickly.
  • Instead of using a uniform distribution for the injected noise, we now use normally-distributed noise. The mean of this distribution converges much more slowly on the original value, when compared to the average of the minimum and maximum value in the case of uniformly-distributed noise.
  • Rather than using a low, fixed amount of noise (0.1%), we’ve refactored the noise injection mechanism to support arbitrary levels of noise injection. This allows us to easily fine-tune noise injection, such that the magnitude of noise increases when using audio nodes that are known to reveal subtle OS or hardware differences through minute differences in sample values.

This noise injection also activates when using Audio Worklets (e.g. AudioWorkletNode ) to read back audio samples.

Screen/Window Metrics

Lastly, for various web APIs that currently directly expose window and screen-related metrics, Safari takes a different approach: instead of the noise-injection-based mitigations described above, entropy is reduced by fixing the results to either hard-coded values, or values that match other APIs.

  • screen.width / screen.height : The screen size is fixed to the values of innerWidth and innerHeight .
  • screenX / screenY : The screen position is fixed to (0, 0) .
  • outerWidth / outerHeight : Like screen size, these values are fixed to innerWidth and innerHeight .

These mitigations also apply when using media queries to indirectly observe the screen size.

Don’t Add Fingerprintable APIs to the Web, Like The Topics API

We have worked for many years with the standards community on improving user privacy of the web platform. There are existing web APIs that are fingerprintable, such as Canvas, and reining in their fingerprintability is a long journey. Especially since we want to ensure existing websites can continue to work well.

It is key for the future privacy of the web to not compound the fingerprinting problem with new, fingerprintable APIs. There are cases where the tradeoff tells us that a rich web experience or enhanced accessibility motivates some level of fingerprintability. But in general, our position is that we should progress the web without increasing fingerprintability.

A recent example where we opposed a new proposal is the Topics API which is now shipping in the Chrome browser . We provided extensive critical feedback as part of the standards process and we’d like to highlight a few pieces here.

The Topics API in a Nutshell

From the proposal :

Any JavaScript can call this function on a webpage. Yes, that includes tracker scripts, advertising scripts, and data broker scripts.

The topics come from a predefined list of hundreds of topics. It’s not the user who picks from these topics, but instead Chrome will record the user’s browsing history over time and deduce interests from it. The user doesn’t get told upfront which topics Chrome has tagged them with or which topics it exposes to which parties. It all happens in the background and by default.

The intent of the API is to help advertisers target users with ads based on each user’s interests even though the current website does not necessarily imply that they have those interests.

The Fingerprinting Problem With the Topics API

A new research paper by Yohan Beugin and Patrick McDaniel from University of Wisconsin-Madison goes into detail on Chrome’s actual implementation of the Topics API.

The authors use large scale real user browsing data (voluntarily donated) to show both how the 5% noise supposed to provide plausible deniability for users can be defeated, and how the Topics API can be used to fingerprint and re-identify users.

“We conclude that an important part of the users from this real dataset are re-identified across websites through only the observations of their topics of interest in our experiment. Thus, the real users from our dataset can be fingerprinted through the Topics API. Moreover, as can be seen, the information leakage and so, privacy violation worsen over time as more users are uniquely re-identified.” —Beugin and McDaniel, University of Wisconsin-Madison

The paper was published at the 2024 IEEE Security and Privacy Workshops (SPW) in May.

Further Privacy Problems With the Topics API

Re-identifying and tracking users is not the only privacy problem with the Topics API. There is also the profiling of users’ cross-site activity. Here’s an example using topics on Chrome’s predefined list .

Imagine in May 2024 you go to news.example where you are a subscriber and have provided your email address. Embedded on the website, dataBroker.example . The data broker has gleaned your email address from the login form and calls the Topics API to learn that you currently have these interests:

  • Event & Studio Photography
  • Luxury Travel

In May 2026 you go to news.example where dataBroker.example calls the Topics API and is told that you now have these interests:

  • Children’s Clothing
  • Family Travel

Finally, in May 2029 you go to news.example where dataBroker.example calls the Topics API and is told that you have these interests:

  • Legal Services
  • Furnished Rentals

You haven’t told any website with access to your email address anything that’s been going on in your family life. But the data broker has been able to read your shifting interests and store them in their permanent profile of you — while you were reading the news.

Now imagine what advanced machine learning and artificial intelligence can deduce about you based on various combinations of interest signals. What patterns will emerge when data brokers and trackers can compare and contrast across large portions of the population? Remember that they can combine the output of the Topics API with any other data points they have available, and it’s the analysis of all of it together that feeds the algorithms that try to draw conclusions about you.

We think the web should not expose such information across websites and we don’t think the browser, i.e. the user agent , should facilitate any such data collection or use.

Privacy Enhancements in Both Browsing Modes

Our defenses against cloaked third-party IP addresses and our partitioning of SessionStorage and blob URLs are enabled by default in both regular browsing and Private Browsing. Here’s how those protections work.

Defending Against Cloaked First Party IP Addresses

In 2020, Intelligent Tracking Prevention (ITP) gained the ability to cap the expiry of cookies set in third-party CNAME-cloaked HTTP responses to 7 days .

This defense did not mitigate cases where IP aliasing is used to cloak third party requests under first party subdomains. ITP now also applies a 7-day cap to the expiry of cookies in responses from cloaked third-party IP addresses. Detection of third-party IP addresses is heuristic, and may change in the future. Currently, two IP addresses are considered different parties if any of the following criteria are met:

  • One IP address is IPv4, while the other is IPv6.
  • If both addresses are IPv4, the length of the common subnet mask is less than 16 bits (half of the full address length).
  • If both addresses are IPv6, the length of the common subnet mask is less than 64 bits (also half of the full address length).

Partitioned SessionStorage and Blob URLs

Websites have many options for how they store information over longer time periods. Session Storage is a storage area in Safari that is scoped to the current tab. When a tab in Safari is closed, all of the session storage associated with it is destroyed. Beginning in Safari 16.1 cross-site Session Storage is partitioned by first-party web site.

Similarly, Blobs are a storage type that allow websites to store raw, file-like data in the browser. A blob can hold almost anything, from simple text to something larger and more complex like a video file. A unique URL can be created for a blob , and that URL can be used to gain access to the associated blob, as long as the blob still exists. These URLs are often referred to as Blob URLs, and a Blob URL’s lifetime is scoped to the document that creates it. Beginning in Safari 17.2, cross-site Blob URLs are partitioned by first-party web site, and first-party Blob URLs are not usable by third parties.

Setting a New Industry Standard

The additional privacy protections of Private Browsing in Safari 17.0, Safari 17.2 and Safari 17.5 set a new bar for user protection. We’re excited for all Safari users and the web itself to benefit from this work!

We love hearing from you! To share your thoughts on Private Browsing 2.0, find John Wilander on Mastodon at @[email protected] or send a reply on X to @webkit . You can also follow WebKit on LinkedIn . If you run into any issues, we welcome your feedback on Safari UI (learn more about filing Feedback ), or your WebKit bug report about web technologies or Web Inspector.

IMAGES

  1. Apply some CSS styles only in the Safari browser

    apply css only for safari

  2. Valid way to target CSS at Safari only?

    apply css only for safari

  3. Css: Css changing css style on safari only

    apply css only for safari

  4. macos

    apply css only for safari

  5. How to "enable CSS" on Safari

    apply css only for safari

  6. How to View Webpage Source CSS and HTML in Safari Mac?

    apply css only for safari

VIDEO

  1. ¿Dónde hacer los mejores safaris?

  2. യൂറോപ്പുകാർ മസാല ഉപയോഗിക്കാറില്ല#turkey #dreamdestinoh #sancharam #santhoshgeorgekulangarasancharam

  3. THAILAND LAOS പൊറോട്ട #safaritv #santhoshgeorgekulangara #malayalam #making #dreamdestinoh #tamil

  4. Now Hiring! Sustainable Safari Maplewood & Burnsville

  5. FLORIAN ALEXANDRU-ZORN: Safari Special Edition performance

  6. അമേരിക്കൻ വിസ ലഭിക്കുന്നതിനുള്ള നുറുങ്ങുകൾ part 1 #dreamdestinoh #sancharam #orusanchariyudediary

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. 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 ...

  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. FabioRosado

    How to apply css rules to safari only Table of Contents. 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 ...

  5. Applying CSS Styles to Safari Browser Only

    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 ...

  6. 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 ...

  7. 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.

  8. 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 ...

  9. CSS rule to style Safari 16.x only

    CSS rule to style Safari 16.x only Safari & Web General WebKit Safari CSS You're now watching this thread. If you've opted in to email or web notifications, you'll be notified when there's activity. Click again to stop watching or visit your profile to manage watched threads and notifications.

  10. 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:

  11. How to Fix CSS Issues on 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 ...

  12. CSS, Safari: Target only Safari browser · GitHub

    works fine on Chrome and Firefox but not on Safari (iOS or MacOS). I am getting a "zero sized error" on Safari. I recently had an expired cert but renewed it using Let's Encrypt. I did not test on Safari after renewal as it worked fine on Chrome. created wordpress website can solve this problem. Thanks in advance!

  13. macos

    color: #00ff00 !important; } and then load it into Safari via the preferences. To reload any changes to the CSS while Safari is open, you need to select None Selected and then re-select your custom file. You'll probably find lots of people on the web that have put lots of effort into similar CSS files. Good luck!

  14. Safari 5 extension for site-specific CSS customisation?

    12. Feel free to install my Stylish extension for Safari (also available in Apple Extensions gallery, Developer section) or fork my project on GitHub. Extension in development, but you can create new styles, search/manage/edit styles from user styles.org database, styles options - only default values supported in current version. Share.

  15. Sometimes you just need to target Safari in your CSS (either ...

    Oh, so these CSS rules specifically work for safari only? Man, frigging Apple. Reply Panda_Photographor • Additional comment actions. similar to responsive design. you write css rules that only apply at specific screen widths, this does the same, but it's css rules that only apply to devices that use Safari Reply ...

  16. 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).

  17. How to make CSS style work in Safari browser?

    Do a hard refresh (on Mac OS using CMD+SHIFT+R) instead of just refreshing the page in order to make sure it gets reloaded correctly. CSS does not get reloaded every time you refresh. - Tim Anthony. Jun 16, 2020 at 12:19. After resetting the safari, only footer fell into place.

  18. CSS3

    CSS3 Media Query to target only Internet Explorer (from IE6 to IE11+), Firefox, Chrome, Safari and/or Edge. If you're a HTML developer you most likely know that there are times when you need to selectively apply some styles to a specific browser, or to a specific version/build of a browser. When such scenarios occur, there are a number of CSS ...

  19. Css

    Css - Apply CSS only for Safari. css safari. Is it possible to add a block of css that I only want to be displayed in Safari and no other browsers? Best Answer. ... For "cellspacing", you can apply the border-spacing CSS property to your table. E.g. for 10px of "cellspacing":

  20. Private Browsing 2.0

    When a tab in Safari is closed, all of the session storage associated with it is destroyed. Beginning in Safari 16.1 cross-site Session Storage is partitioned by first-party web site. Similarly, Blobs are a storage type that allow websites to store raw, file-like data in the browser. A blob can hold almost anything, from simple text to ...

  21. html

    Target safari css, but not chrome [duplicate] Ask Question Asked 10 years, 2 months ago. Modified 10 years, 2 months ago. Viewed 45k times 8 This question ... Is there a way to apply styles to Safari only? Hot Network Questions Maroczy Defence question on f6

  22. css

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