Search code examples
htmlimageslidercentering

How do i center my images on a slideshow using html? (w3 template)


Im developing a website using Html and Css, and I've been trying to center the images inside the slideshow, I've searched all over stack overflow and countless other websites, yet I still couldn't manage to find any solution or answer that uses code similar to the code that I've written.

<title>W3.CSS</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<style>
.mySlides {display:none;}
</style>
<body>


<div class="w3-content w3-display-container">
  <img class="mySlides" src="pancakes.jpeg" style="width: 75%">
  <img class="mySlides" src="acai.jpg" style="width: 75%">
  <img class="mySlides" src="avocado.jpg" style="width: 75%">
  

  <button class="w3-button w3-black w3-display-left" onclick="plusDivs(-1)">&#10094;</button>
  <button class="w3-button w3-black w3-display-right" onclick="plusDivs(1)">&#10095;</button>
</div>

<script>
var slideIndex = 1;
showDivs(slideIndex);

function plusDivs(n) {
  showDivs(slideIndex += n);
}

function showDivs(n) {
  var i;
  var x = document.getElementsByClassName("mySlides");
  if (n > x.length) {slideIndex = 1}
  if (n < 1) {slideIndex = x.length}
  for (i = 0; i < x.length; i++) {
    x[i].style.display = "none";  
  }
  x[slideIndex-1].style.display = "block";  
}
</script>

(Screen Shot 2020-10-02 at 11.45.59 PM.png)


Solution

  • Try this

    <title>W3.CSS</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
    <style>
    .mySlides {display:none;margin:auto}
    </style>
    <body>
    
    
    <div class="w3-content w3-display-container">
      <img class="mySlides" src="pancakes.jpeg">
      <img class="mySlides" src="acai.jpg">
      <img class="mySlides" src="avocado.jpg">
      
    
      <button class="w3-button w3-black w3-display-left" onclick="plusDivs(-1)">&#10094;</button>
      <button class="w3-button w3-black w3-display-right" onclick="plusDivs(1)">&#10095;</button>
    </div>
    
    <script>
    var slideIndex = 1;
    showDivs(slideIndex);
    
    function plusDivs(n) {
      showDivs(slideIndex += n);
    }
    
    function showDivs(n) {
      var i;
      var x = document.getElementsByClassName("mySlides");
      if (n > x.length) {slideIndex = 1}
      if (n < 1) {slideIndex = x.length}
      for (i = 0; i < x.length; i++) {
        x[i].style.display = "none";  
      }
      x[slideIndex-1].style.display = "block";  
    }
    </script>
    

    I have added margin:auto to .mySlides class & I have removed width:75% from img tag