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

jemmyasjd profile image

Setting Up the Multi-Container Application with Docker

Jemmy Dalsaniya - May 27

esproc_spl profile image

A data analysis engine reducing application cost by N times

Judy - May 31

gordinmitya profile image

Disable Dualsence touchpad on Ubuntu

Dmitry Gordin - May 27

jonesrussell profile image

Easy, sure. Quick, never.

Russell Jones - May 31

DEV Community

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

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…

  • 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

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

How to target Safari 16+ with a CSS @supports media query

Easiest method for targeting Safari with CSS in 2024.

I just spent over 30 minutes looking for a way to only target Safari with CSS media queries and could not find a reliable way that works with Safari 17 without also targeting Chrome.

Looking through the compatibility table on caniuse.com you can spot that Safari 16+ has a unique property which is not supported by Chrome or Firefox called hanging-punctuation .

Using that property and -webkit-appearance we can target Safari specifically until any other browser decides to support it.

✦ 2024 Update: You can also chain it with font: -apple-system-body to make this more bulletproof. Thanks to Saber Hayati for the tip.

If you open this page in Safari, the right column will be red.

All Browsers

Safari only

Nice, but why does it also target Arc, Chrome, Firefox, Brave, Internet Explorer, etc. on my iPhone, iPad, or Vision Pro?

Because iOS and iPadOS (and visionOS) use the Mobile Safari rendering engine for all webviews. This means if you are using Chrome or any other “browser” on your iPhone it is still Safari under the hood.

That’s the case until these apps ship with their own rendering engines which will start being possible with iOS 17.4 for the EU.

css target safari

get notified when i write something new or launch a new project right into your inbox.

css target safari

Thanks for your time & attention.

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

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 .

Chris LaChance's logo Chris L a Chance

Site is updating in the open. Rough patches ahead. 😊

New CSS Hacks to Target Safari

Cerfs from L'animal dans la décoration (1897) illustrated by Maurice Pillard Verneuil. Original from the The New York Public Library. Digitally enhanced by rawpixel.

While trying to create a new scalable way to support Dynamic Type on iOS devices , I ran into a snag where it also affected Desktop Safari font sizes. After playing around, I came up with what I believe to be new Safari and iOS CSS targeting hacks.

/* iOS browsers */ @supports(font:-apple-system-body) and (-webkit-touch-callout:default){}   /* Desktop Safari */ @supports(font:-apple-system-body) and (not(-webkit-touch-callout:default)){}

Hope this helps.

Add a comment Cancel

Remember me

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

Styling in the Shadow DOM With CSS Shadow Parts 

Avatar of Ollie Williams

Safari 13.1 just shipped support for CSS Shadow Parts . That means the ::part() selector is now supported in Chrome, Edge, Opera, Safari, and Firefox. We’ll see why it’s useful, but first a recap on shadow DOM encapsulation…

The benefits of shadow DOM encapsulation

I work at giffgaff where we have a wide variety of CSS code that has been written by many different people in many different ways over the years. Let’s consider how this might be problematic. 

Naming collisions

Naming collisions between classes can easily crop up in CSS. One developer might create a class name like .price. Another developer (or even the same one) might use the same class name, without knowing it.

CSS won’t alert you to any error here. Now, any HTML elements with this class will receive the styling intended for two completely different things.

Shadow DOM fixes this problem. CSS-in-JS libraries, like Emotion and styled-components , also solve this issue in a different way by generating random class names, like .bwzfXH . That certainly does help avoid conflicts! However, CSS-in-JS doesn’t prevent anybody from breaking your component in other ways. For example…

Base styles and CSS resets

Styles can be applied using HTML element selectors like <button> and <div> . These styles could break a component. Shadow DOM is the only thing that offers ( almost ) full encapsulation — you can rest assured that your component will look the same, even in a messy  !important  strewn codebase because each component is encapsulated.

I wouldn’t say it’s good practice to style elements this way, but it happens. Even it does, those styles will have no effect on the shadow DOM.

It’s worth noting that inheritable styles like color , font and line-height are still inherited in a shadow DOM. To prevent that, use all: initial  or, preferably, all: revert once it has better browser support.

Let’s look at a common example of CSS applied directly to HTML elements. Consider this code from Eric Meyer’s reset : 

What if the component we’re working with makes use of the user agent’s default values for margin and padding? This reset might cause it to appear broken since those defaults are effectively wiped out.

Shadow DOM is a way to avoid these problems. Shadow DOM allows us to feel fully confident that a component will render as expected, regardless of what codebase it ends up in. Equally, none of the code meant only for a component can inadvertently affect anything else — all without resorting to onerous class naming conventions. Shadow DOM offers a level of encapsulation that can’t be achieved any other way.

Encapsulation is great, but we also want our components to be themeable and customizable. That’s been made far easier with the ::part selector. 

Styling shadow DOM with ::part()

Until now, the only way for CSS to modify the styling of a custom element from outside of the shadow DOM was to use CSS custom properties. In a strict design system where you only want to allow limited changes, that might be ideal. If you want your component to be more versatile, it creates a problem. Every CSS property you want to offer up for styling needs to be defined using a custom property. Just the sound of that seems tedious.

The situation is compounded further if we want to style a component differently based on pseudo-classes, like :hover . Basically, we end up with loads of custom properties. Let’s look at an example from Ionic , an open source set of web components. Just look at all the custom properties defined on the Ionic button component .

Go ahead, I’ll wait.

I counted 23 custom properties. Needless to say, that’s less than ideal.

Here’s an example using  ::part()  to style the element instead. 

In this Pen, I’m simply changing the color , border and background-color properties, but I could use whatever I want without being constrained by what custom properties have been defined. Notice that I can also style different states of the part using pseudo-classes, like :hover and :focus .

The entire component in this button example is being exposed for styling, but if your web component consists of multiple HTML elements, you can expose only selected parts of the component to this sort of styling — hence the name ::part . This stops users of the component from styling any arbitrary element inside the shadow tree. It is up the the component author to expose the parts of the component they explicitly want to. Other parts of the component can be kept visually uniform or make use of custom properties for a more minimal customizability. 

So, how do we set this up for our own components? Let’s look at using ::part to make certain elements of a web component eligible for styling. All we do is add a part attribute on the element we want to be exposed.

In this example the div is customizable with the full gamut of CSS — any CSS property can be changed. The button, however, is locked down — it cannot be visually changed by anybody except the component author.

And the same way an HTML element can have multiple classes, an element can have multiple part names: 

So that’s what we get with ::part : by exposing “parts” of an element we can provide some flexibility in how a web component is used while exercising protection in other areas. Whether it’s your design system, a component library, or what have you, the fact that CSS Shadow Parts are becoming mainstream gives us yet another exciting tool to work with.

Fantastic! Just what I’ve been looking for. A couple of quick questions; – Do you know if there’s a polyfill? – Do you know where it fits in with specificity? Looks like it’s only bested by !important

I think a polyfill is currently wip: https://github.com/PolymerLabs/part-theme Another thing I was missing is this: https://caniuse.com/#feat=mdn-css_selectors_part

Seems like ionic changed the part name to “native” so the example is currently broken.

Didn’t see Nathan’s comment there, but changing ::part(button) to ::part(native) resolved it. Thank you @nathan.

Reader David Waterman writes in:

:part only works through one shadow root – ie you cannot use it for theming an app (unless the app is only one shadow root deep)…you can make it work if you have the control of the parent elements too, by exporting the parts up a level. If you have full control, then that can be exported up to the root dom and effectively allowing theming…but that could lead to a potential mess. Still, these things should be mentions, IMO: https://www.w3.org/TR/css-shadow-parts-1/#exportparts-attr
  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free

Using CSS nesting

The CSS nesting module allows you to write your stylesheets so that they are easier to read, more modular, and more maintainable. As you are not constantly repeating selectors, the file size can also be reduced.

CSS nesting is different from CSS preprocessors such as Sass in that it is parsed by the browser rather than being pre-compiled by a CSS preprocessor. Also, in CSS nesting, the specificity of the & nesting selector is similar to the :is() function; it is calculated using the highest specificity in the associated selector list.

This guide shows different ways to arrange nesting in CSS.

Child selectors

You can use CSS nesting to create child selectors of a parent, which in turn can be used to target child elements of specific parents. This can be done with or without the & nesting selector .

There are certain instances where using the & nesting selector can be necessary or helpful:

  • When joining selectors together, such as using compound selectors or pseudo-classes .
  • For backwards compatibility.
  • As a visual indicator to aid with readability, when seeing the & nesting selector you know that CSS nesting is being used.

In these examples, one without and one with the & nesting selector, the <input> inside the <label> is being styled differently to the <input> that is a sibling of a <label> . This demonstrates the impact of omitting the & nesting selector.

Note: This example demonstrates different outputs in browsers implementing the original specification versus the current nesting spec. The original, pre-August 2023 nesting spec that was implemented in Chrome or Safari, requires the & nesting combinator. If your browser supports the current spec, the output of both examples matches that of the second example.

Without nesting selector

With nesting selector, combinators.

CSS Combinators can also be used with or without the & nesting selector.

Nesting the sibling combinator

In this example, the first paragraph after each <h2> is targeted with the next-sibling combinator ( + ) using CSS nesting.

Compound selectors

When using compound selectors in nested CSS you have to use the & nesting selector. This is because the browser will automatically add whitespace between selectors that do not use the & nesting selector.

In order to target an element with class="a b" the & nesting selector is needed otherwise the whitespace will break the compound selector.

Nesting and compound selectors

In this example the & nesting selector is used to create compound selectors to style elements with multiple classes.

Styles for the .notices to create a column using flexbox layout .

In the CSS code below, nesting is used to create compound selectors both with and without & . The top-level selector defines the basic styles for elements with class="notice" . The & nesting selector is then used to create compound selectors for elements with either class="notice warning" or class="notice success" . Additionally, the use of nesting to create compound selectors without explicitly using & can be seen in the selector .notice .notice-heading::before .

Appended nesting selector

The & nesting selector can also be appended to a nested selector which has the effect of reversing the context.

This can be useful when we have styles for a child element that change when a parent element is given a different class:

As opposed to:

Appending nesting selector

In this example there are 3 cards, one of which is featured. The cards are all exactly the same except the featured card will have an alternative color for the heading. By appending the & nesting selector the style for the .featured .h2 can be nested in the style for the h2 .

In the following CSS, we are creating the styles for .card and .card h2 . Then, in the h2 style block, we nest the .featured class with the & nesting selector appended which creates a style for .card :is(.featured h2) , which is equivalent to :is(.card h2):is(.featured h2) .

Concatenation (is not possible)

In CSS preprocessors such as Sass , it is possible to use nesting to join strings to create new classes. This is common in CSS methodologies such as BEM .

Warning: This is not possible in CSS nesting: when a combinator is not used, the nested selector is treated as a type selector . Allowing concatenation would break this.

In compound selectors , the type selector must come first. Writing &Element (a type selector ) makes the CSS selector, and the entire selector block, invalid. As the type selector must come first, the compound selector must be written as Element& .

Invalid nested style rules

If a nested CSS rule is invalid then all of the enclosed styles will be ignored. This does not affect the parent or preceding rules.

In the following example, there is an invalid selector ( % is not a valid character for selectors). The rule that includes this selector is ignored, but subsequent valid rules are not.

  • CSS nesting module
  • & nesting selector
  • Nesting @ at-rules
  • Nesting and specificity

IMAGES

  1. How to target Safari 16+ with a CSS @supports media query

    css target safari

  2. Valid way to target CSS at Safari only?

    css target safari

  3. We Can Target Only Safari 10 In CSS

    css target safari

  4. Reflected Pixel: CSS Hack Target to Safari & Chrome

    css target safari

  5. HTML : Target safari css, but not chrome

    css target safari

  6. Is their any hack for css, that will only target safari browser.

    css target safari

VIDEO

  1. Sarfa Ranga Skardu

  2. Target Sunday Aug 27

  3. SAFARI INDUSTRIES SHARE TARGET❇️UPPER CIRCUIT HIGH RETURN STOCK SHORT TERM TARGET❇️25/01/2024

  4. SAFARI INDUSTRIES SHARE ANALYSIS FOR TARGET UPDATE🔰SAFARI INDUSTRIES NEWS🌺SHORT TERM 13/01/2024

  5. SAFARI INDUSTRIES SHARE ANALYSIS TARGET NEWS✳️BIG UPDATE CIRCUIT UPPER HIGH RETURN 19/01/2024

  6. safari industries share target analysis stock big update news🪴safari industries news 20/01/2024

COMMENTS

  1. css

    If you want to apply styles to Safari only, not Chrome, you can use some CSS hacks that target the browser-specific prefixes or properties. Learn from the answers and examples of other developers who faced similar challenges with the <progress> element and other HTML elements on Stack Overflow.

  2. css

    Example css fixes, which can be in page or in your external css file etc: /* Safari Mac specific alterations * (relies on class added by js browser detection above), * to take into account different font metrics */ .safari-mac #page4 .section p.fussyDesigner { margin-right: -15px; } .safari-mac #page8 .section-footer { width: 694px; }

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

  4. Applying CSS Styles to Safari Browser Only

    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:.myElement { color: blue; } ::i-block-chrome .myElement { color: red; } Here the default color style will apply as blue in Chrome. But Safari will override it to red.

  5. CSS3

    CSS3 Media Query to target only Internet Explorer (from IE6 to IE11+), Firefox, Chrome, Safari and/or EdgeA 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.

  6. How to target Safari 16+ with a CSS @supports media query

    Looking through the compatibility table on caniuse.com you can spot that Safari 16+ has a unique property which is not supported by Chrome or Firefox called hanging-punctuation. Using that property and -webkit-appearance we can target Safari specifically until any other browser decides to support it. 2024 Update: You can also chain it with font ...

  7. FabioRosado

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

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

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

  10. Detect Safari browser with pure CSS

    You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself. You can also link to another Pen here (use the .css URL Extension) and we'll pull the CSS from that Pen and include it.

  11. New CSS Hacks to Target Safari • Chris LaChance

    New CSS Hacks to Target Safari. June 2021 • Category: Misc. While trying to create a new scalable way to support Dynamic Type on iOS devices, I ran into a snag where it also affected Desktop Safari font sizes. After playing around, I came up with what I believe to be new Safari and iOS CSS targeting hacks. /* iOS browsers */.

  12. 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; } }

  13. Browser Specific Hacks

    If you like to create separate style for chrome and safari, you can use individual css "with" browser detection function. For your question, it might be impossible due of both browser are under the same Webkit browser engine. ... Due to a bug in IE 10 & 11, I needed to target some specific CSS at them. This is where I normally turn to find ...

  14. :target

    The :target CSS pseudo-class represents a unique element (the target element) with an id matching the URL's fragment. css. /* Selects an element with an ID matching the current URL's fragment */ :target { border: 2px solid black; } For example, the following URL has a fragment (denoted by the # sign) that points to an element called section2:

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

    Sometimes you just need to target Safari in your CSS (either on desktop or mobile). Here's a small snippet that I use for that (link of the codepen in comments) comments sorted by Best Top New Controversial Q&A Add a Comment ...

  16. -webkit-prefixed CSS extensions

    Use the CSS flexible box layout with the standard align-items property instead. -webkit-box-direction. Use the CSS flexible box layout with the standard flex-direction property instead. -webkit-box-flex-group. Use the CSS flexible box layout with the standard flex-basis, flex-grow, and flex-shrink properties instead.

  17. Styling in the Shadow DOM With CSS Shadow Parts

    Styling shadow DOM with ::part () Until now, the only way for CSS to modify the styling of a custom element from outside of the shadow DOM was to use CSS custom properties. In a strict design system where you only want to allow limited changes, that might be ideal. If you want your component to be more versatile, it creates a problem.

  18. Using CSS nesting

    You can use CSS nesting to create child selectors of a parent, which in turn can be used to target child elements of specific parents. This can be done with or without the & nesting selector.. There are certain instances where using the & nesting selector can be necessary or helpful:. When joining selectors together, such as using compound selectors or pseudo-classes.

  19. html

    Ran into a problem, where chrome and safari display margin differently. But both of them are webkit, so can't really use a prefix. ... Target safari css, but not chrome [duplicate] Ask Question Asked 10 years ago. ... your answer will target MS Edge as well