Название документа

How TO — CSS/JS Modal

Learn how to create a Modal Box with CSS and JavaScript.

How To Create a Modal Box

A modal is a dialog box/popup window that is displayed on top of the current page:

Step 1) Add HTML:

Example

class=»modal» is a container element for the modal and the div with class=»modal-content» is where you put your modal content (headings, paragraphs, images, etc).

The element with class=»close» should be used to close the modal.

Step 2) Add CSS:

Example

/* The Modal (background) */
.modal display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
>

/* Modal Content/Box */
.modal-content background-color: #fefefe;
margin: 15% auto; /* 15% from the top and centered */
padding: 20px;
border: 1px solid #888;
width: 80%; /* Could be more or less, depending on screen size */
>

/* The Close Button */
.close color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
>

Читайте также:  Меняем фон сайта с помощью HTML - Нубекс

.close:hover,
.close:focus color: black;
text-decoration: none;
cursor: pointer;
>

The .modal class represents the window BEHIND the actual modal box. The height and width is set to 100%, which should create the illusion of a background window.

Add a black background color with opacity.

Set position to fixed; meaning it will move up and down the page when the user scrolls.

It is hidden by default, and should be shown with a click of a button (we’ll cover this later).

The .modal-content class

This is the actual modal box that gets focus. Do whatever you want with it. We have got you started with a border, some padding, and a background color. The margin: 15% auto is used to push the modal box down from the top (15%) and centering it (auto).

We also set the width to 400px — this could be more or less, depending on screen size. We will cover this later.

The .close class

The close button is styled with a large font-size, a specific color and floats to the right. We have also added some styles that will change the color of the close button when the user moves the mouse over it.

Step 3) Add JavaScript:

Example

// Get the modal
var modal = document.getElementById(«myModal»);

// Get the button that opens the modal
var btn = document.getElementById(«myBtn»);

// Get the element that closes the modal
var span = document.getElementsByClassName(«close»)[0];

// When the user clicks on the button, open the modal
btn.onclick = function() modal.style.display = «block»;
>

// When the user clicks on (x), close the modal
span.onclick = function() modal.style.display = «none»;
>

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) if (event.target == modal) modal.style.display = «none»;
>
>

Add a class for modal-header, modal-body and modal-footer:

Example

Some text in the Modal Body

Some other text.

Style the modal header, body and footer, and add animation (slide in the modal):

Example

/* Modal Header */
.modal-header padding: 2px 16px;
background-color: #5cb85c;
color: white;
>

/* Modal Footer */
.modal-footer padding: 2px 16px;
background-color: #5cb85c;
color: white;
>

/* Modal Content */
.modal-content position: relative;
background-color: #fefefe;
margin: auto;
padding: 0;
border: 1px solid #888;
width: 80%;
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
animation-name: animatetop;
animation-duration: 0.4s
>

Bottom Modal («Bottom sheets»)

An example on how to create a full-width modal that slides in from the bottom:

Example

Tip: Also check out Modal Images and Lightbox.

Источник

Всплывающее окно на HTML и CSS

Для вывода важных сообщений или просто изменений, произведённых на сайте, можно использовать всплывающие окна. Всплывающие окна бывают двух видов: обычные и модальные.

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

Посмотреть пример модального окна можно с помощью JavaScript, воспользовавшись методом alert().

Всплывающее окно

Первым шагом создания всплывающего окна является создание элемента (или любого другого элемента) и его оформление:

     .okno  
Всплывающее окошко!

Этот и будет использоваться в качестве всплывающего окна. Теперь мы его скрываем с помощью значения none свойства display и добавляем ссылку, при нажатии на которую будет появляться всплывающее окно:

     #okno < width: 300px; height: 50px; text-align: center; padding: 15px; border: 3px solid #0000cc; border-radius: 10px; color: #0000cc; display: none; >#okno:target  
Всплывающее окошко!
Вызвать всплывающее окно

Используя псевдо-класс :target мы выбираем и применяем стили к элементу, к которому был осуществлён переход. Таким образом после перехода по ссылки значение свойства display элемента сменится с none на block .

Теперь надо расположить посередине страницы, чтобы он стал похож на всплывающее окно. Делаем его абсолютно позиционированным и центрируем его по вертикали и горизонтали:

Следующим шагом будет реализация скрытия окна, при нажатии на любое место страницы или на само окно. Для этого нам нужно расположить элемент внутри элемента :

     #main < display: none; position: absolute; top: 0; left: 0; width: 100%; height: 100%; >#okno < width: 300px; height: 50px; text-align: center; padding: 15px; border: 3px solid #0000cc; border-radius: 10px; color: #0000cc; position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto; >#main:target   
Всплывающее окошко!
Вызвать всплывающее окно

На этом создание простого всплывающего окна закончено.

Модальное окно

Для создания всплывающего модального окна, берём элемент , оформляем его и добавляем ссылку, при нажатии на которую он будет появляться:

     #okno < width: 300px; height: 50px; text-align: center; padding: 15px; border: 3px solid #0000cc; border-radius: 10px; color: #0000cc; display: none; position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto; >#okno:target  
Всплывающее окошко!
Вызвать всплывающее окно

Следующим шагом в создании полноценного модального окна будет добавление кнопки, которая будет скрывать наше окно. Кнопку сделаем из обычной ссылки, добавив её к нашему и оформив:

     #okno < width: 300px; height: 50px; text-align: center; padding: 15px; border: 3px solid #0000cc; border-radius: 10px; color: #0000cc; display: none; position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto; >#okno:target .close < display: inline-block; border: 1px solid #0000cc; color: #0000cc; padding: 0 12px; margin: 10px; text-decoration: none; background: #f2f2f2; font-size: 14pt; cursor:pointer; >.close:hover  
Всплывающее окошко!
Закрыть окно
Вызвать всплывающее окно

Для эффекта затемнения страницы при выводе модального окна, надо поместить весь имеющийся код окна в дополнительный :

Позиционируем родительский и растягиваем его на всю ширину и высоту окна. Задаём ему display: none; и перенаправляем ссылку вызова окна на него.

У дочернего убираем display: none; (он больше не нужен, так как родительский будет скрывать всё, что находится внутри него). В итоге родительский теперь отвечает за отображение модального окна и за затемнение фона страницы, а дочерний только за оформление самого окна:

     #zatemnenie < background: rgba(102, 102, 102, 0.5); width: 100%; height: 100%; position: absolute; top: 0; left: 0; display: none; >#okno < width: 300px; height: 50px; text-align: center; padding: 15px; border: 3px solid #0000cc; border-radius: 10px; color: #0000cc; position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto; background: #fff; >#zatemnenie:target .close < display: inline-block; border: 1px solid #0000cc; color: #0000cc; padding: 0 12px; margin: 10px; text-decoration: none; background: #f2f2f2; font-size: 14pt; cursor:pointer; >.close:hover  
Всплывающее окошко!
Закрыть окно
Вызвать всплывающее окно

Копирование материалов с данного сайта возможно только с разрешения администрации сайта
и при указании прямой активной ссылки на источник.
2011 – 2023 © puzzleweb.ru

Источник

Как создать простое модальное окно на CSS

Как создать модальное окно на чистом CSS

Модальные (всплывающие) окна – это очень популярный элемент интерфейса современных сайтов. Оно может использоваться для вывода различного контента веб-страниц такого, например, как формы (обратной связи, регистрации, авторизации), блоки рекламной информации, изображения, уведомления и др.

В большинстве случаев модальное окно создают на JavaScript. Но его можно создать не только с помощью JavaScript, но и посредством только HTML5 и CSS3.

Демо модального окна

Демонстрацию всплывающего окна, работающего только на HTML5 и CSS3, вы можете посмотреть здесь:

HTML и CSS код модального окна

HTML разметка модального окна:

 

Название

×

Содержимое модального окна.

Ссылка, с помощью которой осуществляется открытие модального окна:

/* стилизация содержимого страницы */ body { font-family: -apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif; font-size: 16px; font-weight: 400; line-height: 1.5; color: #292b2c; background-color: #fff; } /* свойства модального окна по умолчанию */ .modal { position: fixed; /* фиксированное положение */ top: 0; right: 0; bottom: 0; left: 0; background: rgba(0,0,0,0.5); /* цвет фона */ z-index: 1050; opacity: 0; /* по умолчанию модальное окно прозрачно */ -webkit-transition: opacity 200ms ease-in; -moz-transition: opacity 200ms ease-in; transition: opacity 200ms ease-in; /* анимация перехода */ pointer-events: none; /* элемент невидим для событий мыши */ margin: 0; padding: 0; } /* при отображении модального окно */ .modal:target { opacity: 1; /* делаем окно видимым */ pointer-events: auto; /* элемент видим для событий мыши */ overflow-y: auto; /* добавляем прокрутку по y, когда элемент не помещается на страницу */ } /* ширина модального окна и его отступы от экрана */ .modal-dialog { position: relative; width: auto; margin: 10px; } @media (min-width: 576px) { .modal-dialog { max-width: 500px; margin: 30px auto; /* для отображения модального окна по центру */ } } /* свойства для блока, содержащего контент модального окна */ .modal-content { position: relative; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-orient: vertical; -webkit-box-direction: normal; -webkit-flex-direction: column; -ms-flex-direction: column; flex-direction: column; background-color: #fff; -webkit-background-clip: padding-box; background-clip: padding-box; border: 1px solid rgba(0,0,0,.2); border-radius: .3rem; outline: 0; } @media (min-width: 768px) { .modal-content { -webkit-box-shadow: 0 5px 15px rgba(0,0,0,.5); box-shadow: 0 5px 15px rgba(0,0,0,.5); } } /* свойства для заголовка модального окна */ .modal-header { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; -webkit-box-pack: justify; -webkit-justify-content: space-between; -ms-flex-pack: justify; justify-content: space-between; padding: 15px; border-bottom: 1px solid #eceeef; } .modal-title { margin-top: 0; margin-bottom: 0; line-height: 1.5; font-size: 1.25rem; font-weight: 500; } /* свойства для кнопки "Закрыть" */ .close { float: right; font-family: sans-serif; font-size: 24px; font-weight: 700; line-height: 1; color: #000; text-shadow: 0 1px 0 #fff; opacity: .5; text-decoration: none; } /* свойства для кнопки "Закрыть" при нахождении её в фокусе или наведении */ .close:focus, .close:hover { color: #000; text-decoration: none; cursor: pointer; opacity: .75; } /* свойства для блока, содержащего основное содержимое окна */ .modal-body { position: relative; -webkit-box-flex: 1; -webkit-flex: 1 1 auto; -ms-flex: 1 1 auto; flex: 1 1 auto; padding: 15px; overflow: auto; }

Модальное окно на чистом CSS

Если вам необходимо убрать скролл страницы после отображения модального окна, то к элементу body нужно добавить CSS-свойство overflow со значением hidden . А после скрытия модального окна данное свойство убрать у элемента body . Данное действие можно осуществить только с помощью JavaScript:

document.addEventListener("DOMContentLoaded", function(){ var scrollbar = document.body.clientWidth - window.innerWidth + 'px'; console.log(scrollbar); document.querySelector('[href="#openModal"]').addEventListener('click',function(){ document.body.style.overflow = 'hidden'; document.querySelector('#openModal').style.marginLeft = scrollbar; }); document.querySelector('[href="#close"]').addEventListener('click',function(){ document.body.style.overflow = 'visible'; document.querySelector('#openModal').style.marginLeft = '0px'; }); });

Источник

Оцените статью