How to Center Image in WordPress Post When Viewing Mobile and Left When on Desktop

I was making adjustments to a blog post for one of our clients who was experiencing an issue with image alignment. The image was aligned to the left using the default WordPress class "alignleft," which worked fine on desktops. However, when the blog post was viewed on a mobile device, the image alignment looked off. This issue couldn't be fixed with normal CSS alone.

To address this problem, we decided to use vanilla JavaScript, which was first suggested by Bryan Ganzon Granse. We added a custom JavaScript code to handle the image alignment dynamically. The code includes an event listener to detect changes in the window size, whether it switches to desktop, tablet, or mobile. Based on the window size, the code adjusts the class list by removing "alignleft" and adding "aligncenter" for mobile views.

It is better to add a class to the image via the WordPress editor, ensuring that the changes only affect the specific image in the blog post and do not impact other images across the website.

How to Center Image in WordPress Post When Viewing Mobile and Left When on Desktop

document.addEventListener('DOMContentLoaded', function() {

  var figureElement = document.querySelector('.wp-block-image.shaneimg-bg figure.alignleft');


  function updateAlignment() {

    if (window.innerWidth <= 768) { // Mobile view (768px or less)

      if (figureElement.classList.contains('alignleft')) {

        figureElement.classList.remove('alignleft');

        figureElement.classList.add('aligncenter');

      }

    } else { // Desktop and tablet view (more than 768px)

      if (figureElement.classList.contains('aligncenter')) {

        figureElement.classList.remove('aligncenter');

        figureElement.classList.add('alignleft');

      }

    }

  }

  // Initial check
updateAlignment();

  // Update on window resize
window.addEventListener('resize', updateAlignment);

});


Post a Comment

Previous Post Next Post