How to horizontally center images within an absolute div

I've been struggling to center images horizontally within a div on a slideshow I'm working on. The challenge is that my JavaScript requires absolute positioning to run the slideshow, and all my attempts at centering the images have either failed or caused issues with the functionality of the slideshow. Below is the code I'm currently using:

<head>
<style>
#slideshow > div {
    position: absolute;
}
</style>
</head>

<body>
<div id="slideshow">
   <div>
     <img src="http://imagizer.imageshack.us/v2/499x469q90/538/Dn4xDQ.jpg">
   </div>
   <div>
     <img src="http://imagizer.imageshack.us/v2/500x500q90/537/9WJ0XM.jpg">
   </div>
   <div>
     <img src="http://imagizer.imageshack.us/v2/432x432q90/538/xlMaV6.jpg">
   </div>
   <div>
     <img src="http://imagizer.imageshack.us/v2/640x473q90/912/LRvTD5.jpg">
   </div>   
</div>

<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js'>    
</script>
<script>
$("#slideshow > div:gt(0)").hide();
var timesRun = 0;
var interval = setInterval(function(){
    timesRun += 1;
    if(timesRun === 3){
    clearInterval(interval);
}
$('#slideshow > div:first')
    .fadeOut(1000)
    .next()
    .fadeIn(1000)
    .end()
    .appendTo('#slideshow');
}, 3000);
</script>

</body>
</html>

I've created a CodePen showcasing this issue: https://codepen.io/upplepop/pen/jmoMmQ

Answer №1

Here are two methods to achieve it:

1) Establish a width for the parent element absolutely and apply margin: auto; along with display: block to center the image.

$("#slideshow > div:gt(0)").hide();


var timesExecuted = 0;
var interval = setInterval(function(){
timesExecuted += 1;
if(timesExecuted === 3){
clearInterval(interval);
}
$('#slideshow > div:first')
.fadeOut(800)
.next()
.fadeIn(800)
.end()
.appendTo('#slideshow');
}, 2000);
#slideshow > div {
  position: absolute;
  width: 100%;
}

img{
  position: relative;
  margin: auto;
  display: block;
}
<head>
</head>

<body>
<div id="slideshow">
   <div>
     <img src="http://imagizer.imageshack.us/v2/499x469q90/538/Dn4xDQ.jpg">
   </div>
   <div>
     <img src="http://imagizer.imageshack.us/v2/500x500q90/537/9WJ0XM.jpg">
   </div>
   <div>
     <img src="http://imagizer.imageshack.us/v2/432x432q90/538/xlMaV6.jpg">
   </div>
   <div>
     <img src="http://imagizer.imageshack.us/v2/640x473q90/912/LRvTD5.jpg">
   </div>   
</div>

<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js'></script>

</body>

2) Define a width for the absolute parent element and utilize absolute positioning and transform properties for the image.

$("#slideshow > div:gt(0)").hide();


var timesExecuted = 0;
var interval = setInterval(function(){
timesExecuted += 1;
if(timesExecuted === 3){
clearInterval(interval);
}
$('#slideshow > div:first')
.fadeOut(800)
.next()
.fadeIn(800)
.end()
.appendTo('#slideshow');
}, 2000);
#slideshow > div {
  position: absolute;
  width: 100%;
}

img{
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  -webkit-transform: translateX(-50%);
}
<head>
</head>

<body>
<div id="slideshow">
   <div>
     <img src="http://imagizer.imageshack.us/v2/499x469q90/538/Dn4xDQ.jpg">
   </div>
   <div>
     <img src="http://imagizer.imageshack.us/v2/500x500q90/537/9WJ0XM.jpg">
   </div>
   <div>
     <img src="http://imagizer.imageshack.us/v2/432x432q90/538/xlMaV6.jpg">
   </div>
   <div>
     <img src="http://imagizer.imageshack.us/v2/640x473q90/912/LRvTD5.jpg">
   </div>   
</div>

<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js'></script>

</body>

Answer №2

Another option is to include text-align: center; in your div styling. Additionally, ensure that your images are set to either display: inline; or display: inline-block;

$("#slideshow > div:gt(0)").hide();


var timesRun = 0;
var interval = setInterval(function(){
timesRun += 1;
if(timesRun === 3){
clearInterval(interval);
}
$('#slideshow > div:first')
.fadeOut(800)
.next()
.fadeIn(800)
.end()
.appendTo('#slideshow');
}, 2000);
#slideshow > div {
  position: absolute;
  width: 100%;
  text-align: center;
}

img{
  position: relative;
  display: inline-block;
}
<head>
</head>

<body>
<div id="slideshow">
   <div>
     <img src="http://imagizer.imageshack.us/v2/499x469q90/538/Dn4xDQ.jpg">
   </div>
   <div>
     <img src="http://imagizer.imageshack.us/v2/500x500q90/537/9WJ0XM.jpg">
   </div>
   <div>
     <img src="http://imagizer.imageshack.us/v2/432x432q90/538/xlMaV6.jpg">
   </div>
   <div>
     <img src="http://imagizer.imageshack.us/v2/640x473q90/912/LRvTD5.jpg">
   </div>   
</div>

<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js'></script>

</body>

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

Looking to create circular text using HTML, CSS, or JavaScript?

https://i.sstatic.net/pnu0R.png Is there a way to generate curved text in HTML5, CSS3, or JavaScript similar to the image linked above? I've experimented with transform: rotate(45deg); but that just rotates the text without curving it. Additionally, ...

Deleting Empty Session Data

I have set up sessions for my website. In order to initialize the session, I included the following code on every link of the website: session_start(); if(isset($_SESSION['User'])) { //session_start(); $sesvar = $_REQUEST['sid']; } ...

utilizing two input elements within a single form each serving a unique purpose

Hello everyone, I'm seeking assistance on how to code a form with two input element tags, each having different functions. Alas, the solutions provided in this source are not working for me. Here is the troublesome source PHP CODE: <?php $ser ...

Secret message concealed within the depths of my Bootstrap 5 Side Navbar

I have successfully created a side NavBar using Bootstrap 5, but I'm facing an issue where my text is getting hidden behind the navbar. Any suggestions on how I can resolve this? Below is the code for my side Navbar: const Navbar = ({ handleClick, is ...

Is there a way to deactivate all the checkboxes mentioned above if the "None of the above" checkbox is selected?

While browsing websites, I noticed that some have checkbox options for: Family: Wife Husband Son Daughter None. If "None" is selected, the rest of the options are disabled. ...

What is the best method for eliminating a specific line from numerous HTML pages?

I have a series of HTML pages, each with a line at the top that reads: <?xml version="1.0" encoding="UTF-8" ?> When I was working on localhost, the pages opened without any issue. However, now that I have uploaded the files to the server, I am enco ...

Position an image on the top left corner of a div's border

I have a situation where I'm trying to overlay a small square transparent image on the top left border of a div that has a 1px border. The image is 48px by 48px in size and I want it to give the illusion that it's going underneath the top and lef ...

Trouble with CSS loading due to div in Visual Studio MVC

Currently, I am working with Visual Studio 2013 MVC and have a situation regarding the styling of my navbar in _Layout. The navbar includes a messages dropdown menu that utilizes CSS and JS extensively. Interestingly, when I load the messages as a partial ...

Steps for integrating a video into the Bootstrap navigation bar

I've been working on a Bootstrap menu design that features text on the left side and a video on the right. My goal is to make the video extend to the top of the page with a button overlaid, similar to the image I have in mind. However, I've encou ...

The http url on an iPad in the src attribute of an HTML 5 video tag is malfunctioning

Having trouble loading a video on iPad using an http URL in the src attribute of an HTML5 video tag. Both static and dynamic approaches have been attempted, but it works fine on web browsers. Here is an example of the code: Static: <!DOCTYPE html ...

Applying custom CSS designs to images using Thymeleaf

Currently working on a web application using Spring MVC and Thymeleaf for templating. I'm struggling to figure out how to apply rules to an image, especially when using an external CSS file. I have tested code that works: page.html <a class="nav ...

Unable to display the content

Why isn't the text expanding when I click "see more"? Thanks XHTML: <div id="wrap"> <h1>Show/Hide Content</h1> <p> This code snippet demonstrates how to create a show/hide container with links, div eleme ...

Comparing Traditional Tables to Div Tables

Is this process: <table> <tr> <td>Hello</td> <td>World</td> </tr> </table> Achievable with the following code? <div> <div style="display: table-row;"> <di ...

"Composing perfect sentences: The art of incorporating quotes

I am attempting to include text with quotes in a DIV, like so: "All is well that ends well" The text is generated dynamically and I'm using a JavaScript font replacement plugin (CUFON) to add quotes around the text. Sometimes, the ending quote drops ...

Are HTML's Regular Expressions the Equivalent of JavaScript's Regular Expressions?

I have been trying to utilize the pattern="" attribute in HTML to implement regex, but unfortunately, I am unable to locate a comprehensive list of HTML regex parameters. This has led me to ponder whether the syntax for regex in HTML is similar to JavaSc ...

Is there a way in JQuery to apply the CSS of one element to another selected element?

I'm curious if there is a JQuery function available that can be used to transfer the exact CSS styles from one element to another. I want all the CSS properties to be applied without any additional inheritance. For example: <div id="d1"> &l ...

Ways to differentiate between a thumbnail image and a detailed image

On my image-heavy gallery page, I am looking to utilize a thumbnail image that is pre-sized with a maximum width of 200px. The images themselves are quite large, often surpassing 2000 pixels on the longest side. Although I have been using the Bootstrap cl ...

Can someone please help me understand why my CSS transform scale isn't functioning properly?

I've developed a JavaScript function that enlarges a button and then smoothly shrinks it back to its original size. The function successfully changes the color of the button to blue, but for some reason, it's not working with the transform prope ...

The footer on my page seems to be having trouble connecting with the div section above it, causing it to abruptly halt in the middle

After spending a considerable amount of time, I managed to make my footer responsive by sticking it to the bottom of the page regardless of which page you are on. The code that achieved this is as follows: position: absolute; bottom: 0; However, the issu ...

Show results based on the selection of multiple checkboxes upon submission

When creating PHP pages to fetch data from databases, each checkbox is linked to a different page. I want to be able to check one or multiple checkboxes and then click the submit button to display the PHP pages that are linked to the checked checkboxes. Ho ...