How to use a modal in Bootstrap 4
Overview
Modals is a dialog box that is used to display content on a page. It can hold a variety of items, for example, paragraphs, forms, tables, and so on.
Using a modal can enhance the sharing of content on our webpage.
How to create a modal
The first step to creating a modal is to set up a button that will open up the modal. This can be done using the <button> tag with the following properties: type="button", data-toggle="modal", data-target="ModalId"
The next step is to create the three basic containers. We will create the first container with a .modal class and an id. The second container is a child of the first, and it will have a modal-dialog class. The third and final container will have a .modal-content class.
// The three basic containers
<div id="myModal">
<div>
<div>
</div>
</div>
</div>
The next steps to create a modal are as follows:
-
Create another container with the
modal-headerclass. This container will contain two items:-
One of the
h1toh6tags with themodal-titleclass, which is used to display the modal title. -
A button with a
close,data-dismiss="modal", andtype="button"class. These classes are used to set up a clickable button to close the modal. The close entity×is used with this button.
-
-
Create another container with the
modal-bodyclass. This container holds the content of the modal. In this container, we can include any items that we wish to display in it. -
The last container is a container with the
modal-footerclass. This also contains a button that will close the modal. The difference between this button and the one inside themodal-headeris that the button that closes the modal has a button class,.btn, which actually sets up a button.
Code explanation
-
Line 7: We set up a button that opens up our modal.
-
Lines 9–11: We set up our three basic modal containers.
-
Lines 13–16: We set up the modal header with its corresponding content.
-
Lines 18-22: We set up the modal body.
-
Line 24-26: We set up the modal footer.