Skip to main content
Practice

Modal Styling

How can we style the modal overlay (which makes the background blurry) and the interior of the modal?

HTML

<div id="modal">
<div class="modal-content">
<div class="modal-close">&times;</div>
<div id="modal-image"></div>
<div id="modal-text"></div>
</div>
</div>
  1. #modal: The outer container of the entire modal.

  2. .modal-content: The container for the main contents inside the modal.

  3. .modal-close: The button to close the modal. &times; represents a 'X' symbol.

  4. #modal-image: The area designated to display images.

  5. #modal-text: The area designated to display text.


CSS

CSS
#modal {
display: none;
position: fixed;
z-index: 20;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0, 0, 0, 0.4);
}
  • #modal: Sets the background of the entire modal.
    • display: none;: Initially hides the modal from the view.
    • position: fixed;: Keeps the modal fixed on the screen even when scrolling.
    • background-color: rgba(0,0,0,0.4);: Sets a semi-transparent black background making the underlying background slightly visible.

CSS
.modal-content {
display: flex;
flex-direction: column;
gap: 12px;
background-color: white;
margin: auto;
padding: 32px 16px 16px 18px;
width: 95%;
position: relative;
max-width: 500px;
border-radius: 8px;
}
  • .modal-content: Sets the style of the actual modal window.
    • display: flex;: Arranges the internal elements using a flex layout.
    • flex-direction: column;: Arranges elements in a vertical direction.
    • background-color: white;: Sets the background color of the modal window to white.

CSS
.modal-close {
color: #aaaaaa;
position: absolute;
font-size: 32px;
font-weight: bold;
right: 6px;
top: -10px;
}
  • .modal-close: Sets the style of the close button.
    • position: absolute;: Absolutes the button's position in the modal window, which allows positioning it in the top-right corner.

CSS
.modal-close:hover,
.modal-close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
  • Sets the style when the mouse hovers over the close button or it gains focus.

With these CSS settings, the modal window is centered, and the background is semi-transparent black, drawing attention to the modal when it activates.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.