Яндекс.Метрика

Дизайн-журнал №1. Актуальная информация для дизайнеров, веб дизайнеров, программистов и разработчиков сайтов.

Создание галереи изображений с увеличением с использованием только CSS3

13 февраля 2015 | Опубликовано в css | Нет комментариев »

В этом уроке мы создадим галерею изображений с увеличением изображения при нажатии на него. Еще мы добавим кнопку для закрывания увеличенного изображения. И, что самое главное, мы сделаем это на чистом CSS! Лучше всего, чтобы страница с галереей не прокручивалась, так как псевдокласс :target прокрутит страницу до активного элемента, что будет раздражать, если страница может прокручиваться.

Если нужно, мы можем использовать Javascript, чтобы избавиться от этого, а короткий несложный код, решающий эту проблему, можно найти в архиве с исходным кодом.

 


Демонстрация работы – Скачать исходный код

Начнем 

Для начала давайте рассмотрим код HTML. Он состоит из родительского элемента, который содержит несколько блоков класса holder, каждый из которых работает как одно изображение. У каждого блока есть дочерние элементы, такие как закрывающая кнопка, изображение и ссылка, при нажатии на которую изображение увеличивается. Каждая такая ссылка связана с родительским блоком, так что можно использовать псевдокласс :target в коде CSS:

<div id="images-box">
    <div class="holder">
        <div id="image-1" class="image-lightbox">
            <span class="close"><a href="#">X</a></span>
            <img src="1.jpg" alt="earth!">
            <a class="expand" href="#image-1"></a>
        </div>
    </div>
    <div class="holder">
        <div id="image-2" class="image-lightbox">
            <span class="close"><a href="#">X</a></span>
            <img src="2.jpg" alt="earth!">
            <a class="expand" href="#image-2"></a>
        </div>
    </div>
    <div class="holder">
        <div id="image-3" class="image-lightbox">
            <span class="close"><a href="#">X</a></span>
            <img src="3.jpg" alt="earth!">
            <a class="expand" href="#image-3"></a>
        </div>
    </div>
</div>

 

CSS 

Код CSS несложный. Для начала зададим стили для родительских элементов класса holder:

#images-box {
    /* The total width of the image-box, mainly for centering */
    width: 850px;
    margin: 0px auto;
    position: relative;
    top: 70px;
}

.image-lightbox img {
    /* Inherit the width and height from the parent element */
    width: inherit;
    height: inherit;
    z-index: 3000;
}

.holder {
    /* The width and height, you can change these */
    width: 250px;
    height: 166px;
    /* Float left, so everything aligns right */
    float: left;
    margin: 0 20px 0 0;
}
.image-lightbox {
    /* Inherit width and height from the .holder */
    width: inherit;
    height: inherit;
    padding: 10px;
    /* Box shadow */
    box-shadow: 0px 0px 10px rgba(0,0,0,0.1);
    background: #fff;
    border-radius: 5px;
    /* Position absolutely so we can zoom it out later */
    position: absolute;
    top: 0;
    font-family: Arial, sans-serif;
    /* Transitions to provide some eye candy */
    -webkit-transition: all ease-in 0.5s;
    -moz-transition: all ease-in 0.5s;
    -ms-transition: all ease-in 0.5s;
    -o-transition: all ease-in 0.5s;
}

 

После этого нам нужно задать стили внутренним элементам. Мы задали элементам <span> свойство display: none, чтобы закрывающая кнопка появлялась, когда пользователь нажимает на изображение. Ссылка была изменена, чтобы заполнить собой весь родительский элемент, и на него можно было нажимать.

.image-lightbox span {
    display: none;
}

.image-lightbox .expand {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    z-index: 4000;
    background: rgba(0,0,0,0); /* Fixes an IE bug */
    left: 0;
}

.image-lightbox .close {
    position: absolute;
    width: 20px; height: 20px;
    right: 20px; top: 20px;
}

.image-lightbox .close a {
    height: auto; width: auto;
    padding: 5px 10px;
    color: #fff;
    text-decoration: none;
    background: #22272c;
    box-shadow: inset 0px 24px 20px -15px rgba(255, 255, 255, 0.1), inset 0px 0px 10px rgba(0,0,0,0.4), 0px 0px 30px rgba(255,255,255,0.4);
    border-radius: 5px;
    font-weight: bold;
    float: right;
}
.image-lightbox .close a:hover {
    box-shadow: inset 0px -24px 20px -15px rgba(255, 255, 255, 0.01), inset 0px 0px 10px rgba(0,0,0,0.4), 0px 0px 20px rgba(255,255,255,0.4);
}

 

До того, как мы перейдем к тому, что относится к псевдоклассу :target, нужно задать расположение элементам. Если у Вас будет больше изображений, Вам нужно будет добавить им расположение таким же образом.

div#image-1 { left: 0; }
div#image-2 { left: 290px; }
div#image-3 { left: 580px; }

 

Использовать псевдокласс :target не очень сложно. Нужно изменить расположение, свойство z-index и свойства отображения некоторых элементов:

div[id^=image]:target {
    width: 450px;
    height: 300px;
    z-index: 5000;
    top: 50px;
    left: 200px;
}
div[id^=image]:target .close {
    display: block;
}

div[id^=image]:target .expand {
    display: none;
}
div#image-1:target, div#image-2:target, div#image-3:target { left: 200px; }

 

И это все! Вот полный код CSS с комментариями, и можете посмотреть демонстрацию работы.

#images-box {
    /* The total width of the image-box, mainly for centering */
    width: 850px;
    margin: 0px auto;
    position: relative;
    top: 70px;
}

.image-lightbox img {
    /* Inherit the width and height from the parent element */
    width: inherit;
    height: inherit;
}

.holder {
    /* The width and height, you can change these */
    width: 250px;
    height: 166px;
    /* Float left, so everything aligns right */
    float: left;
    margin: 0 20px 0 0;
}

.image-lightbox {
    /* Inherit width and height from the .holder */
    width: inherit;
    height: inherit;
    padding: 10px;
    /* Box shadow */
    box-shadow: 0px 0px 10px rgba(0,0,0,0.1);
    background: #fff;
    border-radius: 5px;
    /* Position absolutely so we can zoom it out later */
    position: absolute;
    top: 0;
    font-family: Arial, sans-serif;
    /* Transitions to provide some eye candy */
    -webkit-transition: all ease-in 0.5s;
    -moz-transition: all ease-in 0.5s;
    -ms-transition: all ease-in 0.5s;
    -o-transition: all ease-in 0.5s;
}

.image-lightbox span {
    display: none;
}

.image-lightbox .expand {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
}

.image-lightbox .close {
    position: absolute;
    width: 20px; height: 20px;
    right: 20px; top: 20px;
}

.image-lightbox .close a {
    height: auto; width: auto;
    padding: 5px 10px;
    color: #fff;
    text-decoration: none;
    background: #22272c;
    box-shadow: inset 0px 24px 20px -15px rgba(255, 255, 255, 0.1), inset 0px 0px 10px rgba(0,0,0,0.4), 0px 0px 30px rgba(255,255,255,0.4);
    border-radius: 5px;
    font-weight: bold;
    float: right;
}

.close a:hover {
    box-shadow: inset 0px -24px 20px -15px rgba(255, 255, 255, 0.01), inset 0px 0px 10px rgba(0,0,0,0.4), 0px 0px 20px rgba(255,255,255,0.4);
}

div[id^=image]:target {
    width: 450px;
    height: 300px;
    z-index: 5000;
    top: 50px;
    left: 200px;
}
div[id^=image]:target .close {
    display: block;
}

div[id^=image]:target .expand {
    display: none;
}

div#image-1:target, div#image-2:target, div#image-3:target { left: 200px; }
div#image-1 { left: 0; }
div#image-2 { left: 290px; }
div#image-3 { left: 580px; }

 

Автор урока Johnny Simpson

Перевод — Дежурка

Смотрите также:




Коментарии запрещены.

[an error occurred while processing the directive]


[an error occurred while processing the directive]