Modal windows html css

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 */
>

Читайте также:  Java runtime environment javase

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

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.

Источник

How To Create a Modal Popup Box with CSS and JavaScript

How To Create a Modal Popup Box with CSS and JavaScript

In this tutorial, we learn how to make a modal with CSS and JavaScript. Our goal is to create a lightweight and simple modal popup box that does not use any third-party libraries and is cross-browser compatible. We will be using vanilla JavaScript without jQuery. Because we will be building it from scratch, we will have full control over how it looks and functions.

Introduction

Modal popups are used pretty frequently on the web. Some popular uses of them include driving newsletter sign ups, displaying notifications/alerts, and handling register and login forms.

Our modal will be generic which means you will be free to use it for whatever purpose you’d like. Here’s what they will look like once finished: The modal before opening.The modal before opening. The modal after opening.The modal after opening.

You can view a live demo of the finished product before continuing on. Now, let’s get started on building this!

HTML Markup

Let’s start with the HTML markup for the modal.

We have three different components here in the markup.

First, we have a simple button which, when clicked on, triggers the modal to open. Then we have the modal’s parent container which houses the modal. Finally, we have the content that will go inside the modal, plus a close button.

To keep things simple, the only content inside the modal is an h1 tag with some text.

CSS Styles

These are the styles we will apply to make our modal look nice and pretty.

 .modal-content < position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background-color: white; padding: 1rem 1.5rem; width: 24rem; border-radius: 0.5rem; >.close-button < float: right; width: 1.5rem; line-height: 1.5rem; text-align: center; cursor: pointer; border-radius: 0.25rem; background-color: lightgray; >.close-button:hover < background-color: darkgray; >.show-modal

The styles here should be pretty simple, but here’s a great class on CSS if you need a refresher.

Let’s break down what we’re doing.

The styles for the modal class makes it so that it creates a semi-transparent dark background color behind the modal when it is active. We stretch it to 100% width and height and set its visibility to hidden so that it doesn’t appear before the user clicks the button.

Then with the modal-content class, we position the actual modal in the center of the screen, with some visual goodies like a border-radius and some padding .

To allow us to close the modal in an elegant way, we have a close button that is just a nicely styled X button at the top-right corner of the modal. We also have a :hover state for the close button so that it changes color when the user hovers over it.

Finally, we have our class that handles styling the modal when it is opened.

All you need to do is give the modal the show-modal class to open it. Removing this class will reset it back to hidden. Some simple JavaScript will handle this toggling for us.

JavaScript Code

To make our modal popup actually work, we will be using a very tiny amount of pure, vanilla JavaScript. Again, we don’t want to use any third-party libraries.

 function windowOnClick(event) < if (event.target === modal) < toggleModal(); >> trigger.addEventListener("click", toggleModal); closeButton.addEventListener("click", toggleModal); window.addEventListener("click", windowOnClick); 
  • When the trigger is clicked, we want to show the modal.
  • When the close button is clicked, we want to hide the modal.
  • When the dark background is clicked, we want to also hide the modal.

Now if we were to press the trigger or the close button, the modal should smoothly animate between the states. It’s all about the pretty animations. 😍

Again, you can click here for a live demo of what we created, or use the live editor below!

Make sure to put your JavaScript code at the bottom of your page so that the elements are processed before you attempt to query for them. Otherwise, the code will give you an error!

Conclusion

Modal boxes are universally popular and now you have an easy implementation to use for yourself that is light-weight and uses no third-party libraries like jQuery. You can use this modal for newsletters, sign-ups, or anything else you want! Hopefully you will enjoy the results and find it useful.

Thumbs up!

Happy coding and thanks for reading! Thumbs up!

Give feedback on this page , tweet at us, or join our Discord !

Getting Started with React

Getting Started with React

Get started with Facebook’s popular React library with this tutorial where you get an overview of React and build a simple app.

Источник

Как создать простое модальное окно на 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'; }); });

Источник

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