Webmasters.BY

Главная Статьи Верстка сайтов Работа с изображениями при помощи CSS3
Работа с изображениями при помощи CSS3
Рейтинг пользователей: / 1
ХудшийЛучший 
28.09.2011 12:53

При использовании свойств box-shadow или border-radius непосредственно на изображении, браузеры могут некорректно отображать заданные нами CSS стили, из-за чего внешний вид блока будет существенно отличаться от задуманного. Однако если использовать изображение в качестве фона, то этой проблемы можно запросто избежать. Из статьи вы узнаете, как с помощью jQuery сделать идеально закругленные углы у изображений, а так же какие еще способы оформления возможны с помощью таких свойств как box-shadow, border-radius и transition.

Смотреть демо

Проблема

Из приведенного ниже примера становится понятно, с какими трудностями мы можем столкнуться при применении css-свойств на изображении. Кроме того каждый браузер отображает готовый элемент по-своему. Firefox не хочет делать углы скругленными, но тень к элементу добавляет, а Chrome или Safari отказываются делать и то и другое.

rounded-corner-problem

Решение Чтобы все свойства работали корректно и во всех браузерах, необходимо использовать изображение в качества фона.
<span class="tag">
<div style="background: url('/image.jpg') no-repeat center center; width:150px; height:150px;"></div></span></code>

Добавление динамики

Для добавления динамики нужно использовать небольшой jQuery скрипт, который будет оборачивать исходное изображение в тег span со стилем image-wrap. Так же применение скрипта сделает наше исходное изображение фоновым и задаст его ширину и высоту.
<script type="text/javascript" src="/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("img").load(function() {
$(this).wrap(function(){
return '<span class="image-wrap ' + $(this).attr('class') + '"
style="position:relative; display:inline-block;
background: url('/ + $(this').attr('src') + ') no-repeat center center;
width: ' + $(this).width() + 'px; height: ' + $(this).height() + 'px;" />';
});
$(this).css("opacity","0");
});
});
</script>

После применения мы получим следующий результат:

<span class="image-wrap" style="position:relative; display:inline-block; background: url('/image.jpg') no-repeat center center; width:150px; height:150px;">
 <img src="image.jpg" style="opacity:0;">
</span>

Примеры (смотреть демо)

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

Эффект окружности

Простой эффект с созданием окружности.

circle-border-radius


.circle .image-wrap {
 -webkit-border-radius: 50em;
 -moz-border-radius: 50em;
 border-radius: 50em;
}</code>

Скругленные углы

Пример со скругленными углами и добавлением тени.

card-style

.card .image-wrap {
 -webkit-box-shadow:
 inset 0 0 1px rgba(0,0,0,.8),
 inset 0 2px 0 rgba(255,255,255,.5),
 inset 0 -1px 0 rgba(0,0,0,.4);
 -moz-box-shadow:
 inset 0 0 1px rgba(0,0,0,.8),
 inset 0 2px 0 rgba(255,255,255,.5),
 inset 0 -1px 0 rgba(0,0,0,.4);
 box-shadow:
 inset 0 0 1px rgba(0,0,0,.8),
 inset 0 2px 0 rgba(255,255,255,.5),
 inset 0 -1px 0 rgba(0,0,0,.4);
 -webkit-border-radius: 20px;
 -moz-border-radius: 20px;
 border-radius: 20px;
} </code>

Рельефный стиль

Добавление небольшого выступа (рельефа) в нижней части изображения.

embossed-style

.embossed .image-wrap {
 -webkit-box-shadow:
 inset 0 0 2px rgba(0,0,0,.8),
 inset 0 2px 0 rgba(255,255,255,.5),
 inset 0 -7px 0 rgba(0,0,0,.6),
 inset 0 -9px 0 rgba(255,255,255,.3);
 -moz-box-shadow:
 inset 0 0 2px rgba(0,0,0,.8),
 inset 0 2px 0 rgba(255,255,255,.5),
 inset 0 -7px 0 rgba(0,0,0,.6),
 inset 0 -9px 0 rgba(255,255,255,.3);
 box-shadow: inset 0 0 2px rgba(0,0,0,.8),
 inset 0 2px 0 rgba(255,255,255,.5),
 inset 0 -7px 0 rgba(0,0,0,.6),
 inset 0 -9px 0 rgba(255,255,255,.3);
 -webkit-border-radius: 20px;
 -moz-border-radius: 20px;
 border-radius: 20px;
}</code>

Рельефный стиль со сглаживанием

Тот же эффект, но с размытием нижней границы в 1px.

soft-embossed

.soft-embossed .image-wrap {
 -webkit-box-shadow:
 inset 0 0 4px rgba(0,0,0,1),
 inset 0 2px 1px rgba(255,255,255,.5),
 inset 0 -9px 2px rgba(0,0,0,.6),
 inset 0 -12px 2px rgba(255,255,255,.3);
 -moz-box-shadow:
 inset 0 0 4px rgba(0,0,0,1),
 inset 0 2px 1px rgba(255,255,255,.5),
 inset 0 -9px 2px rgba(0,0,0,.6),
 inset 0 -12px 2px rgba(255,255,255,.3);
 box-shadow:
 inset 0 0 4px rgba(0,0,0,1),
 inset 0 2px 1px rgba(255,255,255,.5),
 inset 0 -9px 2px rgba(0,0,0,.6),
 inset 0 -12px 2px rgba(255,255,255,.3);
 -webkit-border-radius: 20px;
 -moz-border-radius: 20px;
 border-radius: 20px;
} </code>

Врезанный стиль

Используя свойство box-shadow можно делать эффект врезанного в плоскость изображения.

cutout-effect

.cut-out .image-wrap {
 -webkit-box-shadow:
 0 1px 0 rgba(255,255,255,.2),
 inset 0 4px 5px rgba(0,0,0,.6),
 inset 0 1px 0 rgba(0,0,0,.6);
 -moz-box-shadow:
 0 1px 0 rgba(255,255,255,.2),
 inset 0 4px 5px rgba(0,0,0,.6),
 inset 0 1px 0 rgba(0,0,0,.6);
 box-shadow:
 0 1px 0 rgba(255,255,255,.2),
 inset 0 4px 5px rgba(0,0,0,.6),
 inset 0 1px 0 rgba(0,0,0,.6);
 -webkit-border-radius: 20px;
 -moz-border-radius: 20px;
 border-radius: 20px;
}</code>

Морфинг и подсветка

В этом примере добавляется свойство transition. При наведении мыши происходит подсветка изображения и изменение его формы до окружности. Эффект подсветки создается благодаря свойству box-shadow.

morphing-glowing

.morphing-glowing .image-wrap {
 -webkit-transition: 1s;
 -moz-transition: 1s;
 transition: 1s;
 -webkit-border-radius: 20px;
 -moz-border-radius: 20px;
 border-radius: 20px;
}

.morphing-glowing .image-wrap:hover {
 -webkit-box-shadow: 0 0 20px rgba(255,255,255,.6), inset 0 0 20px rgba(255,255,255,1);
 -moz-box-shadow: 0 0 20px rgba(255,255,255,.6), inset 0 0 20px rgba(255,255,255,1);
 box-shadow: 0 0 20px rgba(255,255,255,.6), inset 0 0 20px rgba(255,255,255,1);
 -webkit-border-radius: 60em;
 -moz-border-radius: 60em;
 border-radius: 60em;
} </code>

Эффект глянца

Пример с наложением градиента на верхнюю часть изображения. Достигается за счет использования псевдоэлемента :after.

glossy-overlay

.glossy .image-wrap {
 -webkit-box-shadow: inset 0 -1px 0 rgba(0,0,0,.5);
 -moz-box-shadow: inset 0 -1px 0 rgba(0,0,0,.5);
 box-shadow: inset 0 -1px 0 rgba(0,0,0,.5);
 -webkit-border-radius: 20px;
 -moz-border-radius: 20px;
 border-radius: 20px;
}

.glossy .image-wrap:after {
 position: absolute;
 content: ' ';
 width: 100%;
 height: 50%;
 top: 0;
 left: 0;
 -webkit-border-radius: 20px;
 -moz-border-radius: 20px;
 border-radius: 20px;
 background: -moz-linear-gradient(top, rgba(255,255,255,0.7) 0%, rgba(255,255,255,.1) 100%);
 background: linear-gradient(top, rgba(255,255,255,0.7) 0%,rgba(255,255,255,.1) 100%);
 background:
 -webkit-gradient(linear, left top, left bottom,
 color-stop(0%,rgba(255,255,255,0.7)),
 color-stop(100%,rgba(255,255,255,.1)));
} </code>

Эффект отражения

Еще один пример с использованием градиента, но на этот раз для создания эффекта отражения.

reflection
<code class="css ruby">.reflection .image-wrap:after {
 position: absolute;
 content: ' ';
 width: 100%;
 height: 30px;
 bottom: -31px;
 left: 0;
 -webkit-border-top-left-radius: 20px;
 -webkit-border-top-right-radius: 20px;
 -moz-border-radius-topleft: 20px;
 -moz-border-radius-topright: 20px;
 border-top-left-radius: 20px;
 border-top-right-radius: 20px;
 background: -moz-linear-gradient(top, rgba(0,0,0,.3) 0%, rgba(255,255,255,0) 100%);
 background: linear-gradient(top, rgba(0,0,0,.3) 0%,rgba(255,255,255,0) 100%);
 background:
 -webkit-gradient(linear, left top, left bottom,
 color-stop(0%,rgba(0,0,0,.3)),
 color-stop(100%,rgba(255,255,255,0)));
}

.reflection .image-wrap:hover {
 position: relative;
 top: -8px;
}</code>

Глянец и отражение

Комбинирование двух выше описанных эффектов.

glossy-reflection

.glossy-reflection .image-wrap {
 -webkit-box-shadow: inset 0 -1px 0 rgba(0,0,0,.5), inset 0 1px 0 rgba(255,255,255,.6);
 -moz-box-shadow: inset 0 -1px 0 rgba(0,0,0,.5), inset 0 1px 0 rgba(255,255,255,.6);
 box-shadow: inset 0 -1px 0 rgba(0,0,0,.5), inset 0 1px 0 rgba(255,255,255,.6);
 -webkit-transition: 1s;
 -moz-transition: 1s;
 transition: 1s;
 -webkit-border-radius: 20px;
 -moz-border-radius: 20px;
 border-radius: 20px;
}

.glossy-reflection .image-wrap:before {
 position: absolute;
 content: ' ';
 width: 100%;
 height: 50%;
 top: 0;
 left: 0;
 -webkit-border-radius: 20px;
 -moz-border-radius: 20px;
 border-radius: 20px;
 background: -moz-linear-gradient(top, rgba(255,255,255,0.7) 0%, rgba(255,255,255,.1) 100%);
 background: linear-gradient(top, rgba(255,255,255,0.7) 0%,rgba(255,255,255,.1) 100%);
 background:
 -webkit-gradient(linear, left top, left bottom,
 color-stop(0%,rgba(255,255,255,0.7)),
 color-stop(100%,rgba(255,255,255,.1)));
}

.glossy-reflection .image-wrap:after {
 position: absolute;
 content: ' ';
 width: 100%;
 height: 30px;
 bottom: -31px;
 left: 0;
 -webkit-border-top-left-radius: 20px;
 -webkit-border-top-right-radius: 20px;
 -moz-border-radius-topleft: 20px;
 -moz-border-radius-topright: 20px;
 border-top-left-radius: 20px;
 border-top-right-radius: 20px;
 background: -moz-linear-gradient(top, rgba(230,230,230,.3) 0%, rgba(230,230,230,0) 100%);
 background: linear-gradient(top, rgba(230,230,230,.3) 0%,rgba(230,230,230,0) 100%);
 background:
 -webkit-gradient(linear, left top, left bottom,
 color-stop(0%,rgba(230,230,230,.3)),
 color-stop(100%,rgba(230,230,230,0)));
} </code>

Эффект ленточки

Использование псевдоэлемента :after для создания эффекта ленточки в верхней части изображения.

tape-style

.tape .image-wrap {
 -webkit-box-shadow:
 inset 0 0 2px rgba(0,0,0,.7),
 inset 0 2px 0 rgba(255,255,255,.3),
 inset 0 -1px 0 rgba(0,0,0,.5),
 0 1px 3px rgba(0,0,0,.4);
 -moz-box-shadow:
 inset 0 0 2px rgba(0,0,0,.7),
 inset 0 2px 0 rgba(255,255,255,.3),
 inset 0 -1px 0 rgba(0,0,0,.5),
 0 1px 3px rgba(0,0,0,.4);
 box-shadow:
 inset 0 0 2px rgba(0,0,0,.7),
 inset 0 2px 0 rgba(255,255,255,.3),
 inset 0 -1px 0 rgba(0,0,0,.5),
 0 1px 3px rgba(0,0,0,.4);
}

.tape .image-wrap:after {
 position: absolute;
 content: ' ';
 width: 60px;
 height: 25px;
 top: -10px;
 left: 50%;
 margin-left: -30px;
 border: solid 1px rgba(137,130,48,.2);
 -webkit-box-shadow: inset 0 1px 0 rgba(255,255,255,.3), 0 1px 0 rgba(0,0,0,.2);
 background: -moz-linear-gradient(top, rgba(254,243,127,.6) 0%, rgba(240,224,54,.6) 100%);
 background: linear-gradient(top, rgba(254,243,127,.6) 0%,rgba(240,224,54,.6) 100%);
 background:
 -webkit-gradient(linear, left top, left bottom,
 color-stop(0%,rgba(254,243,127,.6)),
 color-stop(100%,rgba(240,224,54,.6)));
} </code>

Морфинг и тонирование

При наведении указателя мыши на картинку мы добавляем радиальный градиент используя псевдоэлемент :after.

morphing-tinting
<code class="css ruby">.morphing-tinting .image-wrap {
 position: relative;
 -webkit-transition: 1s;
 -moz-transition: 1s;
 transition: 1s;
 -webkit-border-radius: 20px;
 -moz-border-radius: 20px;
 border-radius: 20px;
}

.morphing-tinting .image-wrap:hover {
 -webkit-border-radius: 30em;
 -moz-border-radius: 30em;
 border-radius: 30em;
}

.morphing-tinting .image-wrap:after {
 position: absolute;
 content: ' ';
 width: 100%;
 height: 100%;
 top: 0;
 left: 0;
 -webkit-transition: 1s;
 -moz-transition: 1s;
 transition: 1s;
 -webkit-border-radius: 30em;
 -moz-border-radius: 30em;
 border-radius: 30em;
}

.morphing-tinting .image-wrap:hover:after  {
 background:
 -webkit-gradient(radial, 50% 50%, 40, 50% 50%, 80,
 from(rgba(0,0,0,0)), to(rgba(0,0,0,1)));
 background: -moz-radial-gradient(50% 50%, circle, rgba(0,0,0,0) 40px, rgba(0,0,0,1) 80px);
}</code>

Эффект окружности с размытием краев

Радиальный градиент можно также использоваться в качестве маски для создания эффекта сглаженных краев.

feather-edge

.feather .image-wrap {
 position: relative;
 -webkit-border-radius: 30em;
 -moz-border-radius: 30em;
 border-radius: 30em;
}

.feather .image-wrap:after  {
 position: absolute;
 content: ' ';
 width: 100%;
 height: 100%;
 top: 0;
 left: 0;
 background:
 -webkit-gradient(radial, 50% 50%, 50, 50% 50%, 70,
 from(rgba(255,255,255,0)), to(rgba(255,255,255,1)));
 background:
 -moz-radial-gradient(50% 50%, circle,
 rgba(255,255,255,0) 50px, rgba(255,255,255,1) 70px);
} </code>

Смотреть демо

Кроссбраузерность

Эти примеры работают во всех браузерах (Chrome, Firefox и Safari), с поддержкой свойств border-radius, box-shadow и псевдоэлементами :before и :after. В остальных браузерах мы просто увидим картинки, без каких либо эффектов.

Источник (англ)

Добавить комментарий


Защитный код
Обновить

Если вы заметили ошибку в тексте новости, пожалуйста, выделите её и нажмите Ctrl+Enter

Если у Вас возникли вопросы, то для скорейшего получения ответа рекомендуем воспользоваться нашим форумом

Обновлено 28.09.2011 14:01
 

Апельсин-1

Голосование

Ваш любимый html-редактор?

Новые файлы

Шпаргалка по HTML5 Canvas

Archive - бесплатный кириллический шрифт

Шпаргалка по HTML5 атрибутам обработчиков событий

См. также

activecloud.ru

TisRef

Баннер
Система Orphus

Кто онлайн

Сейчас 42 гостей онлайн

Комментарии

Статистика