I am unable to align the image in the center, what could be causing it not to center properly?

Why does my code center in mobile view but not in Desktop? How can I solve this issue?

I have tried using

display: block; margin: auto; width:100%;
and text-align: center;, but it did not work.

let $slides, interval, $selectors, $btns, currentIndex, nextIndex;

let cycle = index => {
  let $currentSlide, $nextSlide, $currentSelector, $nextSelector;

  nextIndex = index !== undefined ? index : nextIndex;

  $currentSlide = $($slides.get(currentIndex));
  $currentSelector = $($selectors.get(currentIndex));

  $nextSlide = $($slides.get(nextIndex));
  $nextSelector = $($selectors.get(nextIndex));

  $currentSlide.removeClass("active").css("z-index", "0");

  $nextSlide.addClass("active").css("z-index", "1");

  $currentSelector.removeClass("current");
  $nextSelector.addClass("current");

  currentIndex = index !== undefined ?
    nextIndex :
    currentIndex < $slides.length - 1 ?
    currentIndex + 1 :
    0;

  nextIndex = currentIndex + 1 < $slides.length ? currentIndex + 1 : 0;
};

$(() => {
  currentIndex = 0;
  nextIndex = 1;

  $slides = $(".slide");
  $selectors = $(".selector");
  $btns = $(".btn");

  $slides.first().addClass("active");
  $selectors.first().addClass("current");

  interval = window.setInterval(cycle, 6000);

  $selectors.on("click", e => {
    let target = $selectors.index(e.target);
    if (target !== currentIndex) {
      window.clearInterval(interval);
      cycle(target);
      interval = window.setInterval(cycle, 6000);
    }
  });

  $btns.on("click", e => {
    window.clearInterval(interval);
    if ($(e.target).hasClass("prev")) {
      let target = currentIndex > 0 ? currentIndex - 1 : $slides.length - 1;
      cycle(target);
    } else if ($(e.target).hasClass("next")) {
      cycle();
    }
    interval = window.setInterval(cycle, 6000);
  });
});
#container {
  position: absolute;
  width: 300px;
  height: 300px;
  overflow: hidden;
  background: red;
  text-align: center;
  display: inline-block;
  margin: auto;
  margin-left: -40%;
}

#slides .slide .slide-partial {
  position: absolute;
  width: 100%;
  height: 100%;
  overflow: hidden;
  transition: transform 1s ease-in-out;
  display: block;
  margin: auto;
}

#slides .slide .slide-partial img {
  position: absolute;
  z-index: 1;
  width: 100%;
  height: 100%;
  -o-object-fit: cover;
  object-fit: cover;
  transition: transform 1s ease-in-out;
  display: block;
  margin: auto;
}

#slides .slide .slide-left {
  top: 0;
  left: 0;
  transform: translateX(-100%);
  display: block;
  margin: auto;
}

#slides .slide .slide-left img {
  top: 0;
  right: 0;
  -o-object-position: 100% 50%;
  object-position: 100% 50%;
  transform: translateX(50%);
  display: block;
  margin: auto;
}

#slides .slide.active .slide-partial,
#slides .slide.active .slide-partial img {
  transform: translateX(0);
  display: block;
  margin: auto;
}

#slide-select {
  position: absolute;
  bottom: 20px;
  left: 20px;
  z-index: 100;
  display: flex;
  align-items: center;
  justify-content: space-around;
  font-family: "Reem Kufi", sans-serif;
  font-size: 1.5em;
  font-weight: lighter;
  color: white;
}

#slide-select li {
  position: relative;
  cursor: pointer;
  margin: 0 5px;
}

#slide-select li.prev:hover {
  transform: translateX(-2px);
}

#slide-select li.next:hover {
  transform: translateX(2px);
}

#slide-select .selector {
  height: 14px;
  width: 14px;
  border: 2px solid white;
  background-color: transparent;
  transition: background-color 0.5s ease-in-out;
}

#slide-select .selector.current {
  background-color: white;
}
<div id="mode">
  <div id="container">
    <ul id="slides">
      <li class="slide">
        <div class="slide-partial slide-left"><img src="1.jpg" /></div>

      </li>
      <li class="slide">
        <div class="slide-partial slide-left"><img src="1.jpg" /></div>

      </li>
      <li class="slide">
        <div class="slide-partial slide-left"><img src="1.jpg" /></div>

      </li>
    </ul>
    <ul id="slide-select">
      <li class="btn prev">
        <</li>
          <li class="selector"></li>
          <li class="selector"></li>
          <li class="selector"></li>
          <li class="btn next">></li>
    </ul>
  </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

The current output is:

An image slide with partial left floating.

What I have attempted:

display: inline-block;
margin: auto;
width: 100%;
text-align: center;
/* result: no use /*

Desired Output:

A properly centered image slide.


If possible, please provide an explanation along with the solution.


Answer №1

To perfectly center an element, utilizing display: grid; along with place-items: center; is the most effective method. This technique will align all items within the grid to the center as long as the div has defined width and height.

It's essential to eliminate any styling from the li and ul elements as they may contain margin properties that could disrupt the positioning of inner elements.

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

Join the nested object using the delimiter ';'

My objective is to concatenate all values from an object using a semi-colon as separator. This process works perfectly when the object consists of just one level: obj = { name: "one" additionalInfo: "hello" ... }; Object.values(obj).join(&ap ...

Update the input tag's value dynamically using another input element without the need for jQuery

I am working with 2 input tags Title: <b-input style="width: 50%" v-model="value.title" class="input-element" placeholder="Title" v-on:click="greet" /> Id: <b-input id="id" style="width: 50%" ...

What is the best way to ensure the logo is centered when the screen size reaches 750?

Looking to center the logo on a media screen size breakpoint? View the photo (Here): https://i.stack.imgur.com/UnB2F.png Check out my code below: .logo img { padding: 15px; width: 125px; } <nav> <ul class='nav-bar'> < ...

Encountered difficulties sending JSON data to a REST endpoint using Node.js

Is there a way to bulk insert JSON data into MongoDB using Mongoose? I am aware of the insertMany method, but I'm encountering difficulties with extracting the correct req.body. Below is an image of my setup in Postman. https://i.sstatic.net/xFznd.pn ...

When using the jQuery datepicker on dynamically generated input fields, the selected date automatically updates the first input field

I am currently integrating date inputs with attached datepicker functionality. The issue I am facing is that when I select a date in the first input and proceed to pick another date in the second or subsequent inputs, the last selected date appears in the ...

The method _react.default.useContext does not exist as a function

I am currently working with Material UI Stepper. After using it, I noticed that the functionality is not working properly as expected from their website. To troubleshoot, I added a console.log inside the VerticalLinearStepper method. Upon checking the cons ...

Leveraging Local Storage for Kendo datasource data caching

I am looking to optimize my page by caching the dataset for multiple identical Kendo DropDownLists (MVC flavor) using ajax. My goal is to load the data into local storage when the page loads, and then bind the dropdownlists to this cached data as needed. ...

Scrolling Text Loop with CSS Animation

I am currently working on creating a unique CSS animation that resembles a looped conveyor belt. Essentially, I want the text within a div to disappear off the screen to the right and then reappear from the left. Here's the approach I've taken s ...

What is the method for retrieving the values of multiple numbers entered in table rows using ASP?

I am trying to customize an input field so that the client can add or delete N number of input fields as needed. While I have successfully implemented adding input fields, I am facing difficulty in retrieving values from these dynamically added text fields ...

Randomizing the JSON loop on every page refresh

Having a JSON file containing various data items (as an example) that I am utilizing with handlebars.js to generate templates. The challenge lies in displaying 15 stories (each within their own div) on page load while shuffling their positions upon each r ...

Sending data from Angular to the DOM

Is there a way to dynamically pass a property to an HTML tag using Angular? <div class="my-class" data-start="10"> I am trying to figure out how to pass the value of data-start dynamically. This is for an Angular 5 application. Any advice would be ...

Delete Entries in MongoDB Collection According to Unique User Pairs

I have a collection of messages stored in MongoDB and I need to keep only the latest 500 records for each pair of users. Users are identified by their sentBy and sentTo attributes. /* 1 */ { "_id" : ObjectId("5f1c1b00c62e9b9aafbe1d6c&quo ...

How do I switch the language and voice for the output in Azure's text-to-voice feature?

Looking for some JavaScript assistance with changing language and voice settings in my code. I have tried searching online but haven't found a solution that fits my skill level. If anyone could provide help with modifying the code, it would be greatl ...

Discovering the value of a key within a JSON object by utilizing a String with JQuery

Given a JSON object, the challenge is to extract values based on user input. The input format will be similar to "data.location.type" or "data.location.items[1].address.street". Is it achievable using JQuery? { "data": { "location": { ...

Oops! Smarty encountered a fatal error that wasn't caught

An error occurred while processing the template file "C:\xampp\htdocs\eventos\libs\templates\teste.tpl" on line 9. The error message states: Fatal error: Uncaught exception 'SmartyCompilerException' with message &apo ...

Tips for accessing and displaying JSON data using jQuery

Data in JSON format: [ { "ID":"25", "Serial":"1", "Purchase_id":"8", "Item":"23", "Unit":"1", "HSN":"84212120", "Quantity":"10", "Purchase_rate":"100", ...

What is the reason behind Express serving the static file through the router, while also causing the path to the scripts folder to

Directory Layout app ├── app.js ├── public │   ├── data │   │   └── data.json │   ├── index.html │   └── js │   ├── filter-list.js └── routes └── index.js Setting up ap ...

Is there a way to search through a list and apply filters based on parameters found within a nested object?

I have a list that needs to be filtered based on parameters from advancedSearchFilters, which contains nested objects. The goal is to return a list that matches all or any of the specified parameters. const list = [ { additionalPrices: 0, clien ...

Executing an AJAX request with a specific state in Node.js

Instead of rendering add.jade directly, I have chosen to enhance the user experience by making an AJAX call to the endpoint. This allows me to maintain the URL as localhost:3000/books, rather than localhost:3000/books/add which lacks navigation state for ...

Separating JQuery toggles for a unique user experience

Looking for a way to toggle my contents under separate list items without assigning each content a separate class or id. What's the best method to implement this in a generic way? Check out this demo for an example. ...