04 января 2008 ~ 3193 Комментария

Правильная прозрачность

dfsdfs

Однажды мне понадобилось сделать прозрачные боковые поля для одного дизайна.

Я решил использовать прозрачность css.

Но каково было узнать, что все элементы внутри прозрачного блока тоже становятся прозрачны и это никак не изменить :-(, тогда мне пришлось использовать прозрачный png.

Sexy Beast divx Недавно я наткнулся на замечательную технику позволяющую устранить эту проблему, ею я и хочу с вами любезно поделиться.

Техника заключается в подложке прозрачного блока в основной блок, который вы хотите сделать прозрачным.

 

Вот так выглядит наш блок:

<div id="container">
<h1>Привет, я прозрачный блок</h1>
Текст внутри блока. Текст внутри блока. Текст внутри блока.
</div>

 

Теперь добавим прозрачную подложку:

<div id="container">
<div class="transparency">
<!-- Это прозрачный блок-->
</div>
<div class="content">
<h1>Привет, я прозрачный блок</h1>
Текст внутри блока. Текст внутри блока. Текст внутри блока.
</div>
</div>

 

Теперь перейдем к оформлению css:

#container {
padding:20px;
width:300px;
color:#FFFFFF;
position:relative;
float:left;
margin-left:20px;
overflow:hidden;
}

#container .transparency  {
    opacity:0.5;
    filter:alpha(opacity=50);
    -moz-opacity:0.5;
background-color:#000000;
width:340px;
height:1500px;
position:absolute;
    top:0px;
    left:0px;
z-index:-1;
}  

.content  {
position:relative;
}  

Готово! Теперь все элементы внутри блока не изменят свою прозрачность. Для полного счастья, я решил написать небольшой скрипт на jQuery, который всё автоматизирует.

Вам будет достаточно лишь добавить класс transp к вашему блоку:

<div id="container" class="transp">
<h1>Привет, я прозрачный блок</h1>
Текст внутри блока. Текст внутри блока. Текст внутри блока.
</div>

И конечно, сам jQuery код:

$(document).ready(function() {
$(".transp").wrapInner('<div>').children().addClass("content");
$(".transp .content").before('<div>').prev().addClass("transparency");
});

На мастера jQuery я, конечно, не претендую, но это работает!

 

Посмотреть демо

Скачать демо

3193 Комментария для “Правильная прозрачность”

  1. enternet 4 августа 2008 at 18:21 Permalink

    В опере 9.52 глюк – в среднем блоке текст черный, а не белый.

  2. Demi 5 августа 2008 at 6:12 Permalink

    Спасиба большое

  3. kikaha 5 августа 2008 at 15:57 Permalink

    хоть я и люблю jQuery, но в данном случае наверное можно было обойтись без него. собственно, это не из вредности пишу. на самом деле интересно – есть ли уже тесты по использованию памяти при выполнение нескольких скриптов на одной странице – например, как-то – accordion – 1 штука, ajax запрос – 1 штука, добавление класса в текст – 2 штуки … и так далее. ибо начинаю замечать что при нагромождении jQuery плагинов страничка уже начинает подтормаживать

  4. Я собственной персоной 5 августа 2008 at 16:29 Permalink

    хоть я и люблю jQuery, но в данном случае наверное можно было обойтись без него. собственно, это не из вредности пишу. на самом деле интересно – есть ли уже тесты по использованию памяти при выполнение нескольких скриптов на одной странице – например, как-то – accordion – 1 штука, ajax запрос – 1 штука, добавление класса в текст – 2 штуки … и так далее. ибо начинаю замечать что при нагромождении jQuery плагинов страничка уже начинает подтормаживать

    Это просто был бонус для тех кто уже использует jQuery.

  5. Rodriguez 5 августа 2008 at 18:01 Permalink

    Интересно…. Возьму на заметку…. Спс.

  6. -=Vovan=- 8 августа 2008 at 4:05 Permalink

    В опере 9.52 глюк – в среднем блоке текст черный, а не белый.

    Подозреваю, что блоки следует поменять местами ( поместить под , а не наоборот, как это приведено в примере), хотя я в этом ничерта не понимаю;)

    Автору спасибо! Ценно.

  7. Serge 18 августа 2008 at 3:02 Permalink

    В опере 9.52 глюк – в среднем блоке текст черный, а не белый.

    походу у оперы глюк такой. ибо при прозрачности блока он чёрным шрифт делает.
    уже встречался с этим. ничего не помогло :(

  8. Serge 18 августа 2008 at 3:05 Permalink

    кстати, в примере на jQuery вроде всё ок

  9. Paul 18 августа 2008 at 3:47 Permalink

    В опере 9.52 глюк – в среднем блоке текст черный, а не белый.

    Глюк есть. Но если текст в этом блоке (только в этом) выделить, а потом снять выделение, то текст становится белым :-)

  10. Goracio 22 августа 2008 at 17:27 Permalink

    Всё перепробовал – не вставляется HTML :(

  11. Goracio 22 августа 2008 at 17:50 Permalink

    Нашёл вариант работающий и в Opera 9.51. Правда в качестве подложки используется png http://www.beart.ru/2008/07/png-prozrachnost/

  12. Я собственной персоной 22 августа 2008 at 18:19 Permalink

    Всё перепробовал – не вставляется HTML :(

    Извините за такой косяк. Как будет время, сделаю поддержку вставки кода.
    Все ваши попытки удалил.

  13. Yuriy 29 сентября 2008 at 15:36 Permalink

    полезный тулз для тестирования в большинстве браузеров
    http://browsershots.org/

  14. alexpts 17 мая 2009 at 1:16 Permalink

    height:1500px;
    Т.е. высота блока должна быть заранее известна? А если блок с динамической высотой?

  15. Андриан 6 июня 2009 at 8:25 Permalink

    По поводу чёрного текста, тоже встречался с этим глюком, помогло только устанавливание текста в каждом блоке вручную, именно в каждом. Иначе он становился чёрным там, где цвет не задан конкретно, а только задан в body

  16. Tarvitz 24 сентября 2009 at 6:24 Permalink

    Для opera 10.00 пример нерабочий. transparency блок не отрисовывается, то есть прозрачной подложки нет =(.

    Ну а так спасибо для ФФ можно будет воткнуть как опциональное

  17. Tarvitz 24 сентября 2009 at 7:43 Permalink

    Удалил конфиги оперы, заработало ;). Опера дебажная оч штука >_>

  18. Suzi Brant 24 февраля 2012 at 13:25 Permalink

    Hello, i believe that i noticed you visited my blog thus i got here to “return the choose”.I am attempting to in finding things to enhance my web site!I suppose its adequate to use a few of your concepts!!

  19. Shela Pizzino 25 февраля 2012 at 17:42 Permalink

    Wow, what a video it is! Actually nice feature video, the lesson given in this video is really informative.

  20. Healthy Eating 25 февраля 2012 at 18:46 Permalink

    Good job, I merely happened your site along with wanted to claim that We’ve actually liked searching your site articles. I’ve subscribed to your current nourish and that i i do hope you compose yet again soon!

  21. Allene Bobb 25 февраля 2012 at 20:15 Permalink

    I and my friends watch the soccer game clips at YouTube always, as they have in fastidious quality.

  22. Glen Martin 26 февраля 2012 at 0:11 Permalink

    I have learned some new things as a result of your weblog. One other thing I would like to say is the fact newer laptop os’s tend to allow a lot more memory to be utilized, but they likewise demand more ram simply to work. If your computer can not handle much more memory as well as the newest software requires that storage increase, it can be the time to buy a new PC. Thanks

  23. Rob Summar 26 февраля 2012 at 3:48 Permalink

    I simply want to tell you that I am newbie to blogs and definitely enjoyed your website. Most likely I’m planning to bookmark your website . You definitely have impressive stories. Kudos for sharing your web site.

  24. Charlott Sprock 26 февраля 2012 at 14:04 Permalink

    you have got a terrific weblog right here! would you prefer to make some invite posts on my blog?

  25. Portable Digital Audio Recorders 26 февраля 2012 at 22:05 Permalink

    good post, my spouse and i certainly adore this site, carry on that

  26. Portable Digital Audio Recorders 28 февраля 2012 at 18:52 Permalink

    When I initially commented I clicked the «Notify me when new comments are added» checkbox and now each time a comment is added I get several emails with the same comment. Is there any way you can remove me from that service? Thanks!

  27. Lauralee 29 февраля 2012 at 9:49 Permalink

    Hello outstanding website! Does running a blog like this take a lot of work? I have no knowledge of computer programming but I had been hoping to start my own blog soon. Anyhow, if you have any suggestions or tips for new blog owners please share. I know this is off subject nevertheless I just needed to ask. Many thanks!

  28. Cherelle 29 февраля 2012 at 12:45 Permalink

    I simply want to say I am just beginner to blogs and truly enjoyed your web page. Most likely I’m going to bookmark your blog post . You amazingly have wonderful writings. Appreciate it for revealing your blog site.

  29. Buy scrapebox list 29 февраля 2012 at 15:06 Permalink

    *There is noticeably a bundle to know about this. I assume you made certain nice points in features also.

  30. barbecueelectrique 29 февраля 2012 at 18:48 Permalink

    Very interesting topic, thanks for posting.

  31. camescope hd 29 февраля 2012 at 21:35 Permalink

    I am impressed with this website, rattling I am a big fan.

  32. http://www.ceramicwatches.org/ 29 февраля 2012 at 21:36 Permalink

    I am not real good with English but I find this really easygoing to read.

  33. velo enfant 29 февраля 2012 at 23:03 Permalink

    I like this post, enjoyed this one regards for posting. «Money is a poor man’s credit card.» by Herbert Marshall McLuhan.

  34. montre gps 1 марта 2012 at 0:42 Permalink

    Keep up the great work , I read few articles on this internet site and I believe that your site is really interesting and contains lots of wonderful info .

  35. http://www.chaussuredefoot.net/ 1 марта 2012 at 0:53 Permalink

    Enjoyed reading through this, very good stuff, appreciate it. «It is well to remember that the entire universe, with one trifling exception, is composed of others.» by John Andrew Holmes.

  36. disque dur ssd 1 марта 2012 at 2:23 Permalink

    Would love to constantly get updated great website!

  37. Parsons 1 марта 2012 at 3:21 Permalink

    I do accept as true with all the ideas you’ve offered on your post. They’re very convincing and will definitely work. Nonetheless, the posts are too quick for starters. May you please extend them a bit from next time? Thank you for the post.

  38. Jessia 1 марта 2012 at 4:10 Permalink

    I’m not certain the place you’re getting your information, however good topic. I needs to spend a while finding out more or understanding more. Thank you for great info I was on the lookout for this information for my mission

  39. dumpster rental in waldo 1 марта 2012 at 5:25 Permalink

    Just assumed I’d comment and say neat concept, did you pattern it for on your own? Looks exceptional!

  40. vps hosting 1 марта 2012 at 8:54 Permalink

    After study just a few of the blog posts in your website now, and I truly like your manner of blogging. I bookmarked it to my bookmark web site list and can be checking again soon. Pls try my website as effectively and let me know what you think.

  41. http://select-restaurant.net/ 1 марта 2012 at 10:43 Permalink

    I believe that a simple and unassuming manner of life is finest for everybody, greatest both for the body and the mind.

  42. climatiseur mobile 1 марта 2012 at 12:25 Permalink

    Very interesting information!Perfect just what I was searching for!

  43. free proxy 2012 1 марта 2012 at 13:38 Permalink

    Excellent day! Do you know if they make any plugins to protect against hackers? I’m kinda paranoid about losing everything I’ve worked hard on. Any tips?

  44. white ceramic watches 1 марта 2012 at 17:22 Permalink

    Thanks for the auspicious writeup. It in fact was a entertainment account it. Look complicated to more delivered agreeable from you! However, how could we keep up a correspondence?

  45. compensation consulting firms 1 марта 2012 at 18:50 Permalink

    Great article and straight to the point. I don’t know if this is truly the best place to ask but do you guys have any thoughts on where to employ some professional writers? Thanks in advance :)

  46. film noir 1 марта 2012 at 20:32 Permalink

    Just a smiling visitor here to share the love (:, btw great pattern .

  47. Donn Friske 1 марта 2012 at 21:34 Permalink

    You’ll want to purchase a expert diagnosis of your ears ringing when you begin managing this. A number of the symptoms of tinnitus may also be suggestive of more serious troubles. What’s more, should the examination isn’t ringing in the ears, then you will want in order to treat and also treat it in a several fashion as compared to you’ll ringing in the ears. Some people who definitely have ears ringing locate getting rid of the affliction by making use of noise remedy. You will find there’s uncomplicated try things out that one could try to see when good treatment method will allow you to overcome your own ringing ears. Music a person’s radio stations concerning not one but two areas. It is best to hear your fixed seem if you have updated the idea between areas. In the event the static audio on the airwaves masks your buzzing in the ears or even causes it to be less noticeable (in some measure masks that), and then appear treatment method will likely support your problem.

  48. filma shqiptar 1 марта 2012 at 22:27 Permalink

    Magnificent web site. A lot of useful info here. I’m sending it to several buddies ans also sharing in delicious. And of course, thanks on your effort!

  49. machine a biere 1 марта 2012 at 23:23 Permalink

    I dugg some of you post as I thought they were very beneficial very beneficial

  50. texas car insurance 2 марта 2012 at 2:21 Permalink

    Great ¡V I should certainly pronounce, impressed with your website. I had no trouble navigating through all the tabs and related information ended up being truly easy to do to access. I recently found what I hoped for before you know it in the least. Quite unusual. Is likely to appreciate it for those who add forums or something, site theme . a tones way for your customer to communicate. Nice task..


Оставить комментарий