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

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;
>

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

Читайте также:  Java время в наносекундах

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

Источник

Способы создания окон PopUp

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

Чаще всего такие окна появляются после совершения определенных действий на сайте, например, пользователь нажимает на ссылку «Заказать обратный звонок» и перед ним всплывает форма заказа.

Очень удобно использовать PopUp окна в связке с ajax, но это уже тема другого урока.

Всё больше и больше в сети начинает появляться веб-ресурсов, которые используют всплывающие окна PopUp. В пример можно привести всем знакомые социальные сети. Все лишние данные со скриншотов удалены.

Вконтакте

Facebook

Twitter

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

Постановка задачи(ТЗ)

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

Решение

Способ 1
html
 
Sample Text
Text in Popup
css
* < font-family: Areal; >.b-container < width:200px; height:150px; background-color: #ccc; margin:0px auto; padding:10px; font-size:30px; color: #fff; >.b-popup < width:100%; height: 2000px; background-color: rgba(0,0,0,0.5); overflow:hidden; position:fixed; top:0px; >.b-popup .b-popup-content
Результат:

Очень часто предлагают использовать:

Да, результат получается аналогичный, но из-за того, что у нас задана высота блока «затемнения», появляются полосы прокрутки. Именно поэтому такой метод не подходит.

Способ 2

Этот способ не отличается кардинально от Способа 1, но я считаю его более удобным.

Html (без изменений)
 
Sample Text
Text in Popup
Css
* < font-family: Areal; >.b-container < width:200px; height:150px; background-color: #ccc; margin:0px auto; padding:10px; font-size:30px; color: #fff; >.b-popup < width:100%; min-height:100%; background-color: rgba(0,0,0,0.5); overflow:hidden; position:fixed; top:0px; >.b-popup .b-popup-content
Результат аналогичный

Благодаря свойству: min-height:100%; наш блок «затемнение» обрел ширину в 100% и минимальную высоту в 100% экрана.

Единственным минусом данного способа является то, что Internet Explorer поддерживает данное свойство только с версии 8.0.

Добавление магии на Jquery

Теперь добавим ссылки для скрытия/отображение нашего всплывающего окна.

Для этого необходимо подключить библиотеку JQuery и небольшой скрипт: