- How to Fix CSS Issues on Safari
- Displaying properties in Safari
- Example of making the border-radius property work on Safari:
- Example of making the background-color property work on Safari:
- CSS и iOS Safari
- Свойства
- Фиксы
- Выводы
- How to Fix CSS When It’s Not Working in Safari Browser
- Does Safari support CSS?
- What can I do if CSS doesn’t work in Safari?
- 1. Update your browser
- 2. Clear cache and history
- 3. Validate your CSS code
- How do I make CSS compatible with all browsers?
- Safari rendering bug with CSS transform — a depth sorting / z-index problem? (works in Chrome)
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:
html> html> head> title>Title of the document title> style> div < height: 100px; width: 17%; background: #ccc; border: 4px solid #1c87c9; -webkit-border-radius: 50%; -moz-border-radius: 50%; border-radius: 50%; -webkit-appearance: none; -moz-appearance: none; appearance: none; > style> head> body> h2>Border-radius example h2> div> div> body> html>
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:
html> html> head> title>Title of the document title> style> body < background-color: #8ebc42; -webkit-appearance: none; -moz-appearance: none; appearance: none; > style> head> body> h2>Background-color Property Example h2> p>Lorem ipsum is simply dummy text. p> body> html>
CSS и iOS Safari
Доброго времени суток, дорогие хабрахабровцы!
Всегда хочется, что бы твой сайт выглядел одинаково хорошо на разных устройствах, включая и мобильные. Но, если поведение в браузерах Android во многом предсказуемо, то с iOS возникает ряд «сюрпризов». О них сегодня и поговорим!
Часть примеров уже публиковалась на Хабре, но я все-равно решил включить их в статью. Разделю статью на две части. В первой – приведу список полезных css-свойств для webkit, а во второй поговорим о фиксах проблем, возникающих при версте для iOS Safari.
Свойства
1. -webkit-overflow-scrolling: touch
Это css-свойство добавит плавный скролл в блоках с overflow: scroll. Рекомендую добавлять это свойство везде, где внутри блока может возникать прокрутка, к примеру, в мобильном меню.
2. -webkit-text-size-adjust: none
Отключает масштабирование текста в горизонтальной ориентации.
3. -webkit-tap-highlight-color: #ccc
Устанавливает цвет выделения активного элемента при тапе на нем (a, label). По умолчанию это серый цвет, и часто может быть ни к чему, или выбиваться из общего дизайна.
4. -webkit-appearance: none
Отключает наложение на элементы стилей системы: тени, border-radius и т.д. Применяется для input (но не всех), textarea, и т.д. Удобно, когда надо задать единый вид элементов на всех устройствах.
input[type=text], input[type=submit], textarea
Применяется не только в верстке для Safari.
Данный медиа-запрос позволит отдельно прописывать стили только для устройств, с поддержкой тач. Таким образом, на тач-устройствах можно отключить лишние анимации, ненужные данным типам устройств.
Можно использовать не только в верстке для Safari.
Фиксы
1. background-attachment: fixed
Проблема: background-attachment: fixed не работает в iOS Safari.
Решение: Фиксировать не фон, а блок или псевдоэлемент.
2. Нежелательный скролл модального окна
Проблема: Это довольно редкий случай, но для общей информации, думаю, так же полезно будет знать о нем. Если модальное окно имеет собственную прокрутку и в закрытом состоянии просто установлен отрицательный z-index (и, к примеру, opacity: 0) — то при попытке скролла страницы, модальное окно может перехватить скролл. В результате чего не будет осуществляться прокрутка страницы.
Решение: Добавляем pointer-events: none к модальному окну в закрытом состоянии.
3. Пропадание меню при скролле
Для того, что бы меню «прилипало» к верхней границе экрана при скролле страницы, часто используют следующий прием. Изначально у меню установлено свойство position: absolute, и при достижении верхней границы окна, через js оно меняется на fixed. А при скролле страницы к началу, значение опять меняется на absolute.
Проблема: В Safari на iOS, при смене position с fixed на absolute, меню пропадает с экрана пока скролл не завершится.
Решение: Использовать для меню position: -webkit-sticky. Поведение меню будет сравнимо с вышеописанным, но пропадать ничего не будет! Плюс, не надо использовать js
.nav < . position: absolute; >.nav_fix < position: fixed; >@supports ((position:sticky) or (position:-webkit-sticky)) < .nav, .nav_fix< position: -webkit-sticky; position: sticky; >>
К слову, значение sticky для свойства position сейчас поддерживается большим количеством браузеров, поэтому его можно использовать и в десктопных браузерах.
4. Блок с position: fixed при скролле
Если реализации решений предыдущих проблем я видел на некоторых сайтах, то данная проблема на сайтах встречается постоянно.
Проблема: При скролле в браузере изменяется высота экрана. Отсюда, если при раскрытом меню или модальном окне не блокировать скролл, возникает подобный эффект:
Решение: Нужно сделать следующий «трюк», используя transform.
Величина в 70px покрывает разницу в изменении высоты окна. И только transform позволяет прорисовывать фон элемента за пределами экрана в данной ситуации.
Выводы
А выводов особо нет, просто пользуйтесь ) Если знаете еще полезные css-свойства или «фиксы», применимые на практике, пишите в комментариях!
Update
В свойствах изменен пункт 5. Т.к. media (hover) имеет узкую поддержку. Спасибо dom1n1k за ценное замечание.
How to Fix CSS When It’s Not Working in Safari Browser
Struggling with various browser issues? Try a better option: Opera One You deserve a better browser! Over 300 million people use Opera One daily, a fully-fledged navigation experience coming with various built-in packages, enhanced resource consumption, and great design. Here’s what Opera One can do:
- Optimize resource usage: Opera One uses your Ram more efficiently than Brave
- AI and User Friendly: New feature directly accessible from the sidebar
- No ads: Built-in Ad Blocker speeds up the loading of pages and protects against data-mining
- Gaming friendly: Opera GX is the first and best browser for gamers
- ⇒ Get Opera One
CSS isn’t working in the Safari browser? It can be a real pain, especially if you’re trying to complete a project.
Safari is one of the most popular browsers in the world. It’s available on iOS, macOS, and even Windows computers. It is compatible with most website design software so you can always expect it to deliver efficiency.
However, if you are developing a website or web application and you want to use CSS to style it, then you might have come across a problem such as CSS not loading in Safari.
CSS stands for Cascading Style Sheet and is used to style your website. It is a powerful tool that changes the look and feel of your website.
Does Safari support CSS?
Safari does support CSS and is compatible with most modern browsers. However, because it’s not as popular as Chrome or Firefox, users tend to ignore it.
Why does CSS not work on Safari? If your website is not working in Safari, that means a few things. You either have a CSS error that needs to be fixed or you have a browser compatibility issue.
- Old web browser – If you have an old version of Safari installed, you should update it immediately. The older versions of the browser may have some bugs and glitches which can cause problems with CSS styles. In such cases, you may experience CSS not showing in Safari.
- Wrong syntax code – Syntax refers to the way a code is written so that it can be read by machines or computers. If you are developing a website using HTML5 or XHTML5 then make sure that you have used the proper syntax code correctly and accurately otherwise it won’t work properly on any browser including Safari.
- You’ve used an unknown/unsupported CSS – There are thousands of CSS properties and even more new ones being added all the time, but only a small subset is supported by any browser. If you’re using one that isn’t supported, it won’t work in any browser and you may get a message saying WebKit CSS not working in Safari.
While there is no CSS hack code for Safari, there are some workarounds you can attempt to get it working again on your browser.
What can I do if CSS doesn’t work in Safari?
1. Update your browser
Some PC issues are hard to tackle, especially when it comes to missing or corrupted system files and repositories of your Windows.
Be sure to use a dedicated tool, such as Fortect, which will scan and replace your broken files with their fresh versions from its repository.
First, make sure you’re using the latest version of Safari. You can check for updates by opening the App Store app and looking for an option to update your software.
An updated browser ensures all the latest and stable tools are available at your disposal and that there are no limited functionalities when you try out your codes.
Read more about this topic
2. Clear cache and history
- Navigate to Safari on the menu bar and select Preferences.
- Click on the Advanced tab and check the Show Develop menu in menu bar box.
- Select Develop on the menu bar and hit Empty Caches.
3. Validate your CSS code
The CSS code that is copied from the web is not always correct. Sometimes this is because of a typo and sometimes it’s because of bad CSS coding practices. It’s easy to accidentally paste an invisible character such as a newline or tab, which can break the code.
You can paste your code onto a CSS validator or an HTML editor with a built-in validator. Alternatively, you can type it manually and see if the problem persists.
How do I make CSS compatible with all browsers?
CSS is not inherently compatible with all browsers, because there are many different ways to interpret the same CSS rules.
The best-case scenario to widen your reach is to use CSS as intended. That means using the correct syntax and naming conventions for your properties and values.
Hopefully, this article was able to shed some light on what to do if CSS is not working on your Safari browser.
While you are still here, we’d like to redirect your attention to our comprehensive list of web authoring software that you may find useful when building a website.
Let us know what solution worked for you in the comments section below.
Still experiencing issues?
If the above suggestions have not solved your problem, your computer may experience more severe Windows troubles. We suggest choosing an all-in-one solution like Fortect to fix problems efficiently. After installation, just click the View&Fix button and then press Start Repair.
Safari rendering bug with CSS transform — a depth sorting / z-index problem? (works in Chrome)
For my website I’m using this spiral animation: Codepen This is how it looks like in Chrome (as it is supposed to be): And this is how it looks like in Safari: The css transform looks great in Google Chrome but in Safari it breaks. I tried the following (as mentioned in other forums/threads), but without success:
transform: translateZ(0px); transform-style: flat; transform: translate3d(0,0,0);
Here is the code (same as here Codepen)
$lines = 10; $duration = 4; ul < perspective: 900px; list-style: none; height: 100vh; max-height: 800px; min-height: 400px; text-align: center; >li < position: absolute; top: 0; width: 100%; animation-duration: ($duration * $lines) s; animation-timing-function: linear; animation-iteration-count: infinite; animation-name: spiral-staircase; opacity: 0; >for $i in 0 .. $lines < li:nth-child() < animation-delay: (($duration * $i)) - $duration s; >> for $r in 0 .. ($lines / 2) < li:nth-child() < right: ($r / 2) rem; >li:nth-last-child() < right: ($r / 2) rem; >> @keyframes spiral-staircase < 0% < transform: translateY(40vh) rotateY(-90deg); opacity: 0; >5% < opacity: 1; >45% < opacity: 1; >50% < transform: translateY(0vh) rotateY(90deg); opacity: 0; >100% < transform: translateY(0vh) rotateY(90deg); opacity: 0; >>
It seems to be a bug in Safari. But do you guys have a workaround for? I would deeply appreciate any help!
Edit: If you can reproduce the question (which you should be able to do with the provided Codepen — just open the Codepen once in Chrome and once in Safari) and you don’t have a solution or answer, I would appreciate an upvote for the question (so more people can see it). Because the problem with this question is: it is very specific and I guess only few people can answer it. Therefore more upvotes get this question more attention — and hopefully a solution.