Align the image at the center of the screen with an overlay

Whenever an image is clicked, a lightbox appears. Currently, the image overlay is positioned at the top of the screen, but ideally, it should be centered on the user's screen.

See the code snippet below:

// The following script creates a lightbox
(function() {
  var $lightbox = $("<div class='lightbox'></div>");
  var $img = $("<img>");
  var $caption = $("<p class='caption'></p>");

  // Insert image and caption into the lightbox

  $lightbox
    .append($img)
    .append($caption);

  // Add lighbox to document

  $('body').append($lightbox);

  $('.lightbox-gallery img').click(function(e) {
    e.preventDefault();

    // Extract image link and description
    var src = $(this).attr("src");
    var cap = $(this).attr("alt");
    var txt = $(this).parent().find('.js-text').text()

    // Populate the lightbox with data

    $img.attr('src', src);
    $caption.text(txt);

    // Show lightbox

    $lightbox.fadeIn('fast');

    $lightbox.click(function() {
      $lightbox.fadeOut('fast');
    });
  });

}());
body{
background: linear-gradient(to bottom right, #b81d1d, #5F554C, #E4DFD8);
font-family: "Open Sans", sans-serif;
}
.text {
  display: none;
}
.container{
max-width: 800px;
margin: 5% auto;
padding: 20px;
background-color: #fff;
overflow: hidden;
box-sizing: border-box;
  box-shadow: 0 15px 20px -15px rgba(0, 0, 0, 0.3), 0 35px 50px -25px rgba(0, 0, 0, 0.3), 0 85px 60px -25px rgba(0, 0, 0, 0.1);
}

.text-center{
text-align: center;
margin-bottom: 1em;
}

.lightbox-gallery {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: center;
}

.lightbox-gallery div > img {
  max-width: 100%;
  display: block;
}

.lightbox-gallery div {
  margin: 10px;
  flex-basis: 180px;
}

@media only screen and (max-width: 480px) {
  .lightbox-gallery {
    flex-direction: column;
    align-items: center;
  }

  .lightbox > div {
    margin-bottom: 10px;
  }
}


/*Lightbox CSS*/


.lightbox{
display: none;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,.7);
position: fixed;
top: 0;
left: 0;
z-index: 20;
padding-top: 30px;
box-sizing: border-box;
}

.lightbox img{
display: block;
  margin: auto;
}

.lightbox .caption{
margin: 15px auto;
width: 50%;
text-align: center;
font-size: 1em;
line-height: 1.5;
font-weight: 700;
color: #eee;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h2 class="text-center">Lightbox Gallery</h2>
<div class="lightbox-gallery">
<div>
          <img src="http://placehold.it/300/f1b702/fff&text=image1" alt="">
          <div class="js-text text">Test 1</div>
      </div>
<div><img src="http://placehold.it/300/d2f1b2/222&text=image2" alt="Lorem ipsum dolor sit amet, consectetur adipisicing elit. Maxime accusamus officiis dignissimos doloribus consectetur harum eos sapiente optio aut minima."><div class="js-text text">Test 2</div></div>
<div><img src="http://placehold.it/300/eee/000&text=image3" alt="Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptates veritatis similique, amet, maiores soluta recusandae cupiditate, sed perspiciatis fugit minima, sunt dolores cum earum deserunt illo ipsum!"><div class="js-text text">Test 3</div></div>
<div><img src="http://placehold.it/300/222/fff&text=image4" alt="Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque laudantium dignissimos tenetur eos unde quidem repellat officiis nemo laboriosam necessitatibus deleniti commodi quis aliquid est atque tempora aut, nihil!"><div class="js-text text">Test</div></div>
<div><img src="http://placehold.it/300/b47f99/000&text=image5" alt="Lorem ipsum dolor sit amet, consectetur adipisicing elit. Architecto minus consequatur soluta quaerat itaque, laboriosam quis a facilis, cumque, deleniti quas aperiam voluptate dolore. Enim nostrum sit eaque, porro eligendi illo placeat?"><div class="js-text text">Test</div></div>
<div><img src="http://placehold.it/300/e1d400/000&text=image6" alt="Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sequi suscipit quam, id aliquam totam aperiam quas rem debitis voluptatem pariatur, illo accusamus facilis eius ipsa! Reprehenderit libero, quas iste repudiandae distinctio, quos dignissimos."><div class="js-text text">Test</div></div>
</div>
</div>

You can access the Codepen here:

Codepen URL: https://codepen.io/jonathandion/pen/EmPbvb

Answer №1

Check out this flexbox solution:

For a live demonstration, visit this CodePen link.

// Here's how you can create a lightbox using JavaScript/jQuery
(function() {
  var $lightbox = $("<div class='lightbox'></div>");
  var $img = $("<img>");
  var $caption = $("<p class='caption'></p>");

  // Add image and caption to lightbox

  $lightbox
    .append($img)
    .append($caption);

  // Add lighbox to document

  $('body').append($lightbox);

  $('.lightbox-gallery img').click(function(e) {
    e.preventDefault();

    // Get image link and description
    var src = $(this).attr("src");
    var cap = $(this).attr("alt");
    var txt = $(this).parent().find('.js-text').text()

    // Add data to lighbox

    $img.attr('src', src);
    $caption.text(txt);

    // Show lightbox

    $lightbox.fadeIn('fast').css('display', 'flex');

    $lightbox.click(function() {
      $lightbox.fadeOut('fast');
    });
  });

}());
/* CSS for the lightbox gallery */

... (CSS code continues)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <h2 class="text-center">Lightbox Gallery</h2>

  ... (HTML markup continues)
  
</div>

Answer №2

Make sure to include padding-bottom: 55px; in the .lightbox class and also add height:100% to the .lightbox img class. This should help with your layout.

See below for a fully functional example:

// Custom lightbox script
(function() {
  var $lightbox = $("<div class='lightbox'></div>");
  var $img = $("<img>");
  var $caption = $("<p class='caption'></p>");

  // Add image and caption to lightbox

  $lightbox
    .append($img)
    .append($caption);

  // Append lighbox to document

  $('body').append($lightbox);

  $('.lightbox-gallery img').click(function(e) {
    e.preventDefault();

    // Retrieve image link and description
    var src = $(this).attr("src");
    var cap = $(this).attr("alt");
    var txt = $(this).parent().find('.js-text').text()

    // Populate lightbox with data

    $img.attr('src', src);
    $caption.text(txt);

    // Display lightbox

    $lightbox.fadeIn('fast');

    $lightbox.click(function() {
      $lightbox.fadeOut('fast');
    });
  });

}(jQuery));
body{
background: linear-gradient(to bottom right, #b81d1d, #5F554C, #E4DFD8);
font-family: "Open Sans", sans-serif;
}
.text {
  display: none;
}
.container{
max-width: 800px;
margin: 5% auto;
padding: 20px;
background-color: #fff;
overflow: hidden;
box-sizing: border-box;
  box-shadow: 0 15px 20px -15px rgba(0, 0, 0, 0.3), 0 35px 50px -25px rgba(0, 0, 0, 0.3), 0 85px 60px -25px rgba(0, 0, 0, 0.1);
}

.text-center{
text-align: center;
margin-bottom: 1em;
}

.lightbox-gallery {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: center;
}

.lightbox-gallery div > img {
  max-width: 100%;
  display: block;
}

.lightbox-gallery div {
  margin: 10px;
  flex-basis: 180px;
}

@media only screen and (max-width: 480px) {
  .lightbox-gallery {
    flex-direction: column;
    align-items: center;
  }

  .lightbox > div {
    margin-bottom: 10px;
  }
}


/*Lightbox Styling*/


.lightbox{
 background-color: rgba(0, 0, 0, 0.7);
    bottom: 0;
    box-sizing: border-box;
    display: none;
    height: 100%;
    left: 0;
    padding-bottom: 55px;
    padding-top: 30px;
    position: fixed;
    right: 0;
    top: 0;
    width: 100%;
    z-index: 20;
}

.lightbox img{
display: block;
  margin: auto;
  height:100%;
}

.lightbox .caption{
margin: 15px auto;
width: 50%;
text-align: center;
font-size: 1em;
line-height: 1.5;
font-weight: 700;
color: #eee;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="container">
<h2 class="text-center">Lightbox Gallery</h2>
<div class="lightbox-gallery">
<div>
          <img src="http://placehold.it/300/f1b702/fff&text=image1" alt="">
          <div class="js-text text">Test 1</div>
      </div>
<div><img src="http://placehold.it/300/d2f1b2/222&text=image2" alt="Lorem ipsum dolor sit amet, consectetur adipisicing elit. Maxime accusamus officiis dignissimos doloribus consectetur harum eos sapiente optio aut minima."><div class="js-text text">Test 2</div></div>
<div><img src="http://placehold.it/300/eee/000&text=image3" alt="Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptates veritatis similique, amet, maiores soluta recusandae cupiditate, sed perspiciatis fugit minima, sunt dolores cum earum deserunt illo ipsum!"><div class="js-text text">Test 3</div></div>
<div><img src="http://placehold.it/300/222/fff&text=image4" alt="Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque laudantium dignissimos tenetur eos unde quidem repellat officiis nemo laboriosam necessitatibus deleniti commodi quis aliquid est atque tempora aut, nihil!"><div class="js-text text">Test</div></div>
<div><img src="http://placehold.it/300/b47f99/000&text=image5" alt="Lorem ipsum dolor sit amet, consectetur adipisicing elit. Architecto minus consequatur soluta quaerat itaque, laboriosam quis a facilis, cumque, deleniti quas aperiam voluptate dolore. Enim nostrum sit eaque, porro eligendi illo placeat?"><div class="js-text text">Test</div></div>
<div><img src="http://placehold.it/300/e1d400/000&text=image6" alt="Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sequi suscipit quam, id aliquam totam aperiam quas rem debitis voluptatem pariatur, illo accusamus facilis eius ipsa! Reprehenderit libero, quas iste repudiandae distinctio, quos dignissimos."><div class="js-text text">Test</div></div>
</div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

drawImage - Maintain scale while resizing

I am currently working on resizing an image using drawImage while maintaining the scale. Here is what I have so far... window.onload = function() { var c = document.getElementById("myCanvas"); var ctx = c.getContext(" ...

Sending PHP arrays to JavaScript using AJAX

My array is being displayed as a list instead of a javascript array. How can I resolve this issue? I tried using JSON.parse as suggested in another answer, but it did not work. Below is the javascript code: var data = { "action": "test" ...

Issue occurred in module.js:341 while attempting to include android platform to ionic using command line

For my hybrid app development using the Ionic framework, I made sure to install all required dependencies like node.js and cordova. Following their Getting started guide, I reached step 3 which instructs running this command within the app directory: > ...

Validation for a datepicker embedded within a table

I'm facing a challenge and need some assistance. I want to validate if the "FROM (DATE)" is greater than the "TO (DATE)" without disabling the date selection, but instead prompting the user if the condition is not met. Any insights or solutions would ...

Adjust the text placement on the toggle switch to turn it On or Off

I am looking to create a toggle switch with a small size. I found some code on Stack Overflow that I tried but it didn't work as expected. The code snippet I attempted to use is from another helpful post. My goal is to have the "on" text align to th ...

Combine each module using grunt and then compress

Looking to achieve this using Grunt. My current file structure is as follows: /app --app.js --/module1 ----module1.js ----module1Model.js --/module2 ----module2.js ----module2Model.js How can I bundle and minify each module into a single file to appear ...

Ways to modify color while user moves the screen

I'm working with some jQuery code that changes the colors of elements as the user scrolls down, and I want it to revert back to the original color when scrolling back up. However, the script is not behaving as expected... Here is the original working ...

jQuery's removeClass and addClass functions seem to be unresponsive

One approach I've taken is using jQuery to dynamically add or remove classes. Specifically, I have an image that should toggle when clicked: <div class="col-6 text-right mb-3"> <span class="hover-it cursor-pointer"> ...

Eliminate the standard border line from a div element

While working on creating shapes in React using CSS, I encountered an irritating issue with a ring design that I'm attempting to create. I can't seem to get rid of the default border around the circle shape I've created. I've tried usin ...

React throws an error message when the update depth surpasses its maximum limit

I am facing an issue with my container setup where the child container is handling states and receiving props from the parent. The problem arises when I have two select statements in which onChange sets the state in the child container, causing it to re-re ...

ability to reach the sub-element dictionaries in typescript

class ProvinciaComponent extends CatalogoGenerico implements OnInit, AfterViewInit { page: Page = new Page({sort: {field: 'description', dir: 'asc'}}); dataSource: ProvinciaDataSource; columns = ['codprovi ...

Tips for showing a different div in the chat window after submitting the form

My index html file features a chat window designed like this: https://i.sstatic.net/PPGoy.png Below the submit button is an area to input text. How can I hide or disable this section and enable it only after the form is filled and the submit button is cl ...

Encountering an issue in the tmp directory while deploying an Angular App with Gitlab CI

Hello there, I am currently facing a challenge while attempting to deploy my Angular application on Heroku through Gitlab CI. The issue revolves around an API key that is stored in the Angular's environment file. Despite creating the necessary folder ...

What method should I use to retrieve the content of this particular paragraph element?

My goal is to extract a summary of a specific data type, such as Axes, using the jsdom library. Here's how I attempted to achieve this: const Jsdom = require('jsdom'); const { JSDOM } = Jsdom; const Axios = require('axios'); async ...

Differences between ES6 class static method and regular function

When working with NodeJS, I am planning to create some utility functions. I have two options in mind. The first option involves using the traditional approach: module.exports = { random: () => Math.random(), }; Alternatively, I could use an ES6 c ...

What is the proper way to invoke a function using a JQuery GET request?

Currently, my task involves authenticating a user using jQuery by calling back to a function on the server-side code. This is what I have accomplished so far: $.get('Authenticate.aspx', function (data){ var auth = data.toString(); } ...

The Maginific popup feature appears to be malfunctioning

I'm currently working on a website and I've encountered an issue. After clicking on the search icon, a search window should open as shown in this image, but I'm getting an error in the console: index.php:113 Uncaught TypeError: $(...).magnif ...

Enhancing Redux with numerous data inputs

Despite my efforts, I am facing an issue where I cannot change the values of two inputs in Redux as intended. // Within my component <Input label="name" value={initialUser.name} onChange={(e) => dispatch(onChangeInputAction(e))} name=" ...

When you click, you will be directed to the specific details of the object

I have a recipe component that displays a list of recipes from my database and a recipe-detail component that should show the details of a selected recipe. What I aim to achieve is that when someone clicks on a recipe name, they are routed to the recipe-de ...

Ember JS - Sharing information between different components

Working with Ember JS version 2.12.0 I've developed a component that triggers an action on click and receives specific data. Now, I'm faced with the challenge of passing this data to another component. Is there a method for achieving this as the ...