Правильная прозрачность
Однажды мне понадобилось сделать прозрачные боковые поля для одного дизайна.
Я решил использовать прозрачность css.
Но каково было узнать, что все элементы внутри прозрачного блока тоже становятся прозрачны и это никак не изменить :-(, тогда мне пришлось использовать прозрачный png.
Недавно я наткнулся на замечательную технику позволяющую устранить эту проблему, ею я и хочу с вами любезно поделиться.
Техника заключается в подложке прозрачного блока в основной блок, который вы хотите сделать прозрачным.
Вот так выглядит наш блок:
<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 я, конечно, не претендую, но это работает!

В опере 9.52 глюк – в среднем блоке текст черный, а не белый.
Спасиба большое
хоть я и люблю jQuery, но в данном случае наверное можно было обойтись без него. собственно, это не из вредности пишу. на самом деле интересно – есть ли уже тесты по использованию памяти при выполнение нескольких скриптов на одной странице – например, как-то – accordion – 1 штука, ajax запрос – 1 штука, добавление класса в текст – 2 штуки … и так далее. ибо начинаю замечать что при нагромождении jQuery плагинов страничка уже начинает подтормаживать
Это просто был бонус для тех кто уже использует jQuery.
Интересно…. Возьму на заметку…. Спс.
Подозреваю, что блоки следует поменять местами ( поместить под , а не наоборот, как это приведено в примере), хотя я в этом ничерта не понимаю;)
Автору спасибо! Ценно.
походу у оперы глюк такой. ибо при прозрачности блока он чёрным шрифт делает.
уже встречался с этим. ничего не помогло :(
кстати, в примере на jQuery вроде всё ок
Глюк есть. Но если текст в этом блоке (только в этом) выделить, а потом снять выделение, то текст становится белым :-)
Всё перепробовал – не вставляется HTML :(
Нашёл вариант работающий и в Opera 9.51. Правда в качестве подложки используется pnghttp://www.beart.ru/2008/07/png-prozrachnost/
Извините за такой косяк. Как будет время, сделаю поддержку вставки кода.
Все ваши попытки удалил.
полезный тулз для тестирования в большинстве браузеров
http://browsershots.org/
height:1500px;
Т.е. высота блока должна быть заранее известна? А если блок с динамической высотой?
По поводу чёрного текста, тоже встречался с этим глюком, помогло только устанавливание текста в каждом блоке вручную, именно в каждом. Иначе он становился чёрным там, где цвет не задан конкретно, а только задан в body
Для opera 10.00 пример нерабочий. transparency блок не отрисовывается, то есть прозрачной подложки нет =(.
Ну а так спасибо для ФФ можно будет воткнуть как опциональное
Удалил конфиги оперы, заработало ;). Опера дебажная оч штука >_>
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!!
Wow, what a video it is! Actually nice feature video, the lesson given in this video is really informative.
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!
I and my friends watch the soccer game clips at YouTube always, as they have in fastidious quality.
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
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.
you have got a terrific weblog right here! would you prefer to make some invite posts on my blog?
good post, my spouse and i certainly adore this site, carry on that
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!
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!
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.
*There is noticeably a bundle to know about this. I assume you made certain nice points in features also.
Very interesting topic, thanks for posting.
I am impressed with this website, rattling I am a big fan.
I am not real good with English but I find this really easygoing to read.
I like this post, enjoyed this one regards for posting. «Money is a poor man’s credit card.» by Herbert Marshall McLuhan.
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 .
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.
Would love to constantly get updated great website!
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.
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
Just assumed I’d comment and say neat concept, did you pattern it for on your own? Looks exceptional!
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.
I believe that a simple and unassuming manner of life is finest for everybody, greatest both for the body and the mind.
Very interesting information!Perfect just what I was searching for!
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?
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?
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 :)
Just a smiling visitor here to share the love (:, btw great pattern .
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.
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!
I dugg some of you post as I thought they were very beneficial very beneficial
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..