Css-хак под любой браузер — легко!
Обычно я не беру материалы с популярных источников, не читать же моим читателям одно и тоже по сто раз, но это будет исключение, не могу удержатся поделится с остальными такой полезной вещью.
С помощью этого хака можно будет изменять вид вашего сайта(редактируемой странички) для любого браузера и любой ОС в отдельности.
Смотрим код:
<script type="text/javascript">
var cssFix = function(){
var u = navigator.userAgent.toLowerCase(),
addClass = function(el,val){
if(!el.className) {
el.className = val;
} else {
var newCl = el.className;
newCl+=(" "+val);
el.className = newCl;
}
},
is = function(t){return (u.indexOf(t)!=-1)};
addClass(document.getElementsByTagName('html')[0],[
(!(/opera|webtv/i.test(u))&&/msie (\d)/.test(u))?('ie ie'+RegExp.$1)
:is('firefox/2')?'gecko ff2'
:is('firefox/3')?'gecko ff3'
:is('gecko/')?'gecko'
:is('opera/9')?'opera opera9':/opera (\d)/.test(u)?'opera opera'+RegExp.$1
:is('konqueror')?'konqueror'
:is('applewebkit/')?'webkit safari'
:is('mozilla/')?'gecko':'',
(is('x11')||is('linux'))?' linux'
:is('mac')?' mac'
:is('win')?' win':''
].join(" "));
}();
</script>
Думаю после просмотра кода Вы поняли в чем суть этого скрипта.
Изменять css свойства для разных браузеров мы будем с помощью следующих css классов:
Классы ОС:
- .win - Windows
- .linux - Linux
- .mac - MacOS
Классы браузеров:
- .ie - все версии ИЕ
- .ie8 - ИЕ 8.х
- .ie7 - ИЕ 7.x
- .ie6 - ИЕ 6.x
- .ie5 - ИЕ 5.x
- .gecko - все версии фаерфокса, и остальные гекко-браузеры
- .ff2 - фаерфокс 2
- .ff3 - фаерфокс 3
- .opera - все версии оперы
- .opera8 - опера 8.x
- .opera9 - опера 9.x
- .konqueror - konqueror
- .safari - сафари
К примеру на нужно изменить цвет шрифта для третьей версии Firefox запущенной под Windows.
.win .ff3 {
color: #000000;
}
На мой взгляд, просто и гениально. Единственный минус этого способа — javascript, так что все юзеры с отключенным javascript'ом отсекаются.
Используйте на здоровье! ;-)

Спасибо
Особенно радует «Написал Я собственной персоной» ;)
Подумываю убрать этот кусочек кода в вордпресс.
Тогда никого это не будет радовать (-:
Приеду — уберу.
Эмм, а мне казалось, что когда откуда-то берут статью, ставят ссылку а источник :)
Я когда на хабре прочитал, еле удержался от копипаста :)
а ссылку на хабраисточник? А то некрасиво ж…
2aratak, ну автор в самом начале поста написал что не претендует на своё авторство. А вот ссылка – правило хорошего тона. В принципе настоящий автор, не требовал ссылку при цитировании.
значит это не автор а копипастер
значит будем навариваться на деликатных нежадных авторах, которые вместо здрасьте сразу в лоб не требуют ссылку? я когда копипастю – мне пофигу – просил автор, или требовал – я поставлю ссылку на источник – для меня самого это важно в первую очередь.
«Я помню чудное мгновение» – это очень красиво, но даже тому, кто никогда не читал Пушкина, я не буду тереть что это мои стихи – мне самому стыдно и неприятно будет, да, таким мама воспитала.
Как сказал кто-то умный, если оно есть в интернет, значит у этого есть бесконечное количество копий.
Извините, у меня день рождения был, писал заметку на скорую руку, и честно говоря, забыл про ссылку ;-)
Поздравляю :), как говорится с прошедшим.
поздравляемъ
[кстати, прикрути кнопку удаления сессии в комментировании]
кстати
.win .ff3 {
color: #000000;
}
не будет работать так как оба класа установлены у html а в css идет клас за класом селектор :)
Вот это то что давно искал спасибо.
Смысл от этого, тогда уж проще сделать отдельные файлы для каждого браузера, чтобы не грузить бестолковый для меня стиль IE / Safari / Oper’ы и еще кучки браузеров если я сижу в FF, да и вобще …
Спасибо))Сохранил на винт))
Неплохо продумано, но в основном все проблемы связаны с IE. Поэтому под все остальные браузеры можно не париться, потому что они обычно отображают так, как показывает опера или файерфокс. Для меня IE – это заноза в заднице, все там как-то криво.
ненавижу код без отступов ;-( уж в одну строку всё написали бы
>Неплохо продумано, но в основном все проблемы связаны с IE. Поэтому под все остальные браузеры можно не париться
Хе хе. А под другие ОС? Сравните ФФ 3 под мак и под вынь =)
Полезный скрипт. Активно юзаю подобный.
А если у меня к примеру. Как его совместить с win. ie.?
Запарился разбираться с хаками для IE. Половина того что пишут миф.
А за это большое человеческое спасибо.
A few very nice things on this web site, I like that.
great post, my partner and i definitely enjoy this amazing site, carry on it
I just want to tell you that I’m newbie to blogging and site-building and seriously loved this blog site. Likely I’m going to bookmark your blog . You certainly come with superb articles. With thanks for revealing your website page.
hope you never stop! This is one of the best blogs I have ever read. You have got some mad skill here, man. I just hope that you dont lose your style because youre definitely one of the coolest bloggers out there. Please keep it up because the internet needs someone like you spreading the word.
Do you mind if I quote a few of your posts as long as I provide credit and sources back to your webpage? My blog is in the exact same niche as yours and my visitors would genuinely benefit from a lot of the information you provide here. Please let me know if this ok with you. Thank you!
A truly exciting examine, I could possibly not concur entirely, but you do make some actually legitimate points.
Very excellent visual appeal on this web site, I’d rate it 10.
I really like your writing style, good info , appreciate it for putting up : D.
You are my inhalation, I own few web logs and rarely run out from post :). «Actions lie louder than words.» by Carolyn Wells.
I like this post, enjoyed this one regards for putting up.
Hey, you used to write great, but the last few posts have been kinda boring… I miss your super writings. Past few posts are just a little out of track! come on!»In politics stupidity is not a handicap.» by Napoleon Bonaparte.
I loved up to you will receive performed right here. The cartoon is attractive, your authored subject matter stylish. nonetheless, you command get got an nervousness over that you would like be handing over the following. sick for sure come further in the past again as precisely the same nearly very continuously inside case you shield this increase.
You made some nice points there. I looked on the internet for the subject and found most people will go along with with your site.
Wow, thanks for the sample sale tip – never knew something like that even existed…
Hi, where can I subscribe to your weblog? I like it, thanksCu
It’s vital to get yourself a specialized decides your own buzzing in the ears before you begin healing the item. Most of the ear ringing can also be an indication of rather more serious difficulties. In addition, should the medical diagnosis is not tinnitus, then you will want in order to medicate or treat it inside of a unique way as compared to you would ringing in ears. Some people who definitely have ringing ears discover relief from their own affliction by utilizing appear treatment. You will find there’s easy research that you can concept when seem treatment method will allow you to cope with your own ringing ears. Track ones radio stations in between two gas stops. You’ll want to hear your static sound once you have tuned that concerning gas stops. When the interferance appear from your airwaves goggles your current ringing ears or perhaps will make it less noticeable (somewhat masks this), next appear treatment method will most likely support your lack of control.
I just couldn’t depart your site prior to suggesting that I actually enjoyed the standard information a person provide for your visitors? Is gonna be back often to check up on new posts
I like the valuable info you provide inside your articles. I’ll bookmark your weblog and check once more here regularly. I’m quite certain I’ll learn several new stuff proper here! Good luck for the next!
Some really prize blog posts on this site, saved to bookmarks .
Needed to write you that very small remark to be able to thank you so much over again on your magnificent knowledge you’ve contributed at this time. It is certainly pretty open-handed of people like you to present unhampered all that a number of us would’ve distributed as an electronic book to make some dough for their own end, particularly considering the fact that you could possibly have done it in the event you wanted. Those concepts in addition acted like the good way to comprehend some people have similar passion really like my own to understand a whole lot more regarding this matter. I am sure there are a lot more pleasant sessions up front for individuals who browse through your blog post.
Some truly excellent posts on this internet site, thanks for contribution. «Careful. We don’t want to learn from this.» by Bill Watterson.
I was just searching for this information for a while. After 6 hours of continuous Googleing, finally I got it in your website. I wonder what is the lack of Google strategy that do not rank this type of informative websites in top of the list. Usually the top web sites are full of garbage.
Keep up the fantastic piece of work, I read few blog posts on this site and I conceive that your blog is real interesting and has got bands of fantastic info.
Really nice design and great articles , very little else we need : D.
I don’t usually comment but I gotta tell thankyou for the post on this special one : D.
We are a bunch of volunteers and opening a new scheme in our community. Your web site provided us with useful info to paintings on. You’ve done an impressive job and our entire group will likely be thankful to you.
I have discovered some new items from your web-site about personal computers. Another thing I have always considered is that laptop computers have become an item that each family must have for most reasons. They offer convenient ways in which to organize the home, pay bills, search for information, study, tune in to music and perhaps watch television shows. An innovative approach to complete all of these tasks is a laptop computer. These pc’s are mobile ones, small, highly effective and easily transportable.
I like this site very much so much fantastic info . «She refused to be bored chiefly because she wasnt boring.» by Zelda Fitzgerald.