Nov52006
Sombra em imagem com DOM e CSS
Image drop shadow with DOM and CSS
Inspirado pelos artigos do A List Apart, há um tempo venho pensando numa solução para criar sombras em imagens sem atrapalhar minha semântica, ou seja, com o mínimo de manipulação da marcação em torno da imagem. Depois de alguns estudos e testes, cheguei num resultado onde é necessário utilizar apenas uma classe para criar as sombras.
Inspired by two articles of A List Apart, I come thinking about a solution to create drop shadows on images without confuse my semantic, that is, with the minimum of manipulation in markup around the image. After some studies and tests, I arrived in a result where it’s necessary to use only one class to create the drop shadows.
Como funciona
How it works
O conceito da criação das sombras é o seguinte:
- Adicionar um
div, via DOM, em volta da imagem; - Setar este
divcom a mesma largura da imagem, para que a sombra fique proporcional à largura da mesma; - Inserir um background que simule uma sombra neste
divvia CSS; - Deslocar, levemente, a imagem para obter o tamanho de sombra desejado, também via CSS.
- Pronto!
- Insert a
div, with DOM, around the image; - Set this
divwith the same width of the image; - Insert a shadow background on
divwith CSS; - Dislocate, lightly, the image to get the desired size of drop shadow, also with CSS.
- That’s all!
Veja um exemplo:
Take a look:
<img src="../avatar-80x80.gif" class="shadow" />
Resulta em:
Results in:
![]()
Os códigos
The codes
Criando o container, via DOM, para receber a sombra da imagem.
setImageDropShadow = function (searchClass,tag) {var browser=navigator.appName;var agent = navigator.userAgent;var b_version=navigator.appVersion;var version=parseFloat(b_version);var opera = falseif(agent.indexOf("Opera")!=-1){var versionindex=agent.indexOf("Opera")+6;if (parseInt(agent.charAt(versionindex))>=8)opera = true;}var els = document.getElementsByTagName(tag);var pattern = new RegExp("\\b"+searchClass+"\\b");for (i = 0; i < els.length; i++) {if ( pattern.test(els[i].className) ) {var NewDiv = document.createElement('div');NewDiv.className = "shadow-container";if (((browser=="Microsoft Internet Explorer") && (version>=4) && (!agent.indexOf("MSIE 7") != -1)) || (opera)) { // Fix IE 6 and Opera width problemNewDiv.style.width = (els[i].width - 4).toString() + “px”;} else {NewDiv.style.width = (6 + els[i].width).toString() + “px”;}var parentDiv = els[i].parentNode;parentDiv.insertBefore(NewDiv, els[i]);NewDiv.appendChild(els[i]);}}}window.onload = function() {setImageDropShadow('shadow','img');};
Estilizando a sombra.
.shadow-container {position: relative;background: url(bg-small-shadow.png);}.shadow-container img {position: relative;display: block;top: -3px;left: -3px;margin: 0;padding: 2px;background: #fff;border: 1px solid #e1e1e1;}
Para criar a sombra, utilizei uma imagem de 20×20px, em tom de cinza claro (#d8d8d8) e 50% de transparência. A imagem pode ser vista aqui!
Get the drop shadow background here!
Detalhe importante! A parte em negrito, a seguir, é a que determina a distância da sombra em relação à imagem. Quanto menores os valores inseridos para top e left, maior será a distância da sombra em relação à imagem.
Important detail! The lines in boldface, below, are that determine the distance between the image and the drop shadow. Change the values for better use.
.shadow-container img {position: relative;display: block;top: -3px;left: -3px;margin: 0;padding: 2px;background: #fff;border: 1px solid #e1e1e1;}
Tudo o que você precisa para usar sombras em suas imagens
All you need to work with it
Esta solução foi testada no Opera 9.x, Firefox 1.5.0.7, IE 6.0, IE 7.0 RC1 e Safari 2.0.4.
Reportes de erros, bugs, e, pricipalmente, sugestões são muito bem-vindos. ;)

RamonPage.com . Web na ponta do lápis » Blog Archive » Mostrar-esconder conteúdo via DOM V.2 - 6/11/06 às 8:39 am
[...] Texto largo « Sombra em imagem com DOM e CSS [...]
Pablo - 5/01/07 às 1:53 pm
Cara muito boa esta função… Parabéns
Mas…
Como eu faria para aplicar este shadow em uma div ???
gadarf - 22/04/08 às 7:51 pm
Muito interessante mesmo.