Centered image

I am working on a website and struggling to center the image on all screen sizes.

I attempted the following code:-

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" language="javascript">
        window.onload = function () {
            var rotator = document.getElementById("rotator");
            var images = rotator.getElementsByTagName("img");
            for (var i = 1; i < images.length; i++) {
                images[i].style.display = "none";
            }
            var counter = 1;
            setInterval(function () {
                for (var i = 0; i < images.length; i++) {
                    images[i].style.display = "none";
                }
                images[counter].style.display = "block";
                counter++;
                if (counter == images.length) {
                    counter = 0;
                }
            }, 1000);
        };
    </script>
<style>
.pg{
  top: 50%;
  left: 50%;
  position: absolute;
}
img
{
  display:block;
  margin:auto;
}
</style>
</head>
<body>
    <form id="form1">
    <div class="pg" id="rotator">
        <img alt="" src="img/logo.png" />
        <img alt="" src="img/aip.png" />
    </div>
    </form>
</body>
</html>

Unfortunately, the above code did not achieve what I wanted.

I would appreciate any assistance!

If you have any codes that could help me center the image better, please share them with me.

I seem to be having trouble centering the image using my current code, so any guidance is greatly appreciated.

The CSS I am currently using is as follows:-

<style>
    .pg{
  top: 50%;
  left: 50%;
  position: absolute;
    }
    img
{
  display:block;
  margin:auto;
}
    </style>

Answer №1

If you're looking to center content both horizontally and vertically, consider the following approach: I've added height, width, and border properties for clarity. For responsiveness across different screen sizes, use media queries to adjust image widths accordingly.

window.onload = function () {
            var rotator = document.getElementById("rotator");
            var images = rotator.getElementsByTagName("img");
            for (var i = 1; i < images.length; i++) {
                images[i].style.display = "none";
            }
            var counter = 1;
            setInterval(function () {
                for (var i = 0; i < images.length; i++) {
                    images[i].style.display = "none";
                }
                images[counter].style.display = "block";
                counter++;
                if (counter == images.length) {
                    counter = 0;
                }
            }, 1000);
        };
.pg {
    display:flex;
    align-items:center;
    justify-content:center;
    height:200px;
    border: 1px solid red;
    
}
img {
       width:80px;
    }
    <form id="form1">
    <div class="pg" id="rotator">
      <div class="img" id="rotator">
        <img alt="" src="https://i.sstatic.net/pBxRp.png" />
        <img alt="" src="https://i.sstatic.net/5GIJP.png" />
      </div>
    </div>
    </form>

Answer №2

give this a try

    img
    {
      display:flex;
      justify-content:center;
      max-width:100%;
    }

every image will be perfectly centered.

Answer №3

Make sure to include text-align: center; in the pg class and add margin: 0 auto; to all img tags.

.pg {
  text-align: center;
}

.pg img{
  margin: 0 auto;
}

Check out this fiddle for reference.

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

The HTML textarea is not updating properly when using jQuery's keypress event

I am facing an issue with my forms on a webpage, each containing an html textarea: <textarea name="Comment" class="inputTextArea">Hello World!</textarea> There is a javascript event handler that automatically submits the fo ...

CSS font-face is not functioning as expected

I'm experiencing issues with importing a CSS font, and I'm puzzled as to why it's not working. The specific font in question is 'deadjim.ttf' and it is located within my main public_html directory. I have confirmed that the file p ...

access various paths to distinct iframes

<?php // Specify the directory path, can be either absolute or relative $dirPath = "C:/xampp/htdocs/statistics/pdf/"; // Open the specified directory and check if it's opened successfully if ($handle = opendir($dirPath)) { // Keep readin ...

Why is there a CSS reference failure in Express and how can it be resolved?

Below, you'll find a simple express server I've put together: // check out my basic Express server var express = require("express"); var app = express(); var bodyparser = require("body-parser"); app.use("/public/", express.static("./public/")); ...

Encountered a 404 error while handling the Express 4 module, indicating that the 'html' module could not be

I need to update my express app to handle 404 (and 500) errors by displaying HTML instead of plain text. I have been able to show text to the client for 404 errors, but now I want to show HTML instead. My 404.html file is located in the /app directory. Cu ...

Need help with JQuery mouseOver fading in twice when you only want it to fade in

The version can be displayed here. I'm looking to have the current text fade away and the new text fade in. Strangely, it seems to fade in twice for some reason. $(window).load(function(){ var originalTitle = $('.Pinctitle').text(); $(&apo ...

"Maximizing the functionality of HTML forms by incorporating PHP for efficient data retrieval

I have been exploring different approaches but I'm struggling to get this to function correctly. As a beginner, I am using form elements with dropdown menus to receive user input and then send the data via email. Here is the HTML and PHP code: <fo ...

Problem with logo in MVC4 apps

I'm working on incorporating a logo into my MVC 4 website. When the logo is clicked, it should navigate to the home screen. In order to achieve this, I've added the following code snippet in the _Layout.cshtml file. <a href='<%= Url.A ...

Is there a way to eliminate the number spinner in Angular specifically for certain input fields?

I am facing an issue where I need to remove the numeric spinner from only a few selected inputs. By adding the following code snippet to my styles.scss file, I was able to successfully remove the spinner: /* Chrome, Safari, Edge, Opera */ input[matinput]: ...

Reducing the size of CSS classes and IDs

I am searching for a way to automatically compress classes and ids in an .html file. This specific file is generated through a sequence of gulp commands. I attempted to use the Munch command line application, but it had adverse effects on the file by elimi ...

Adjust the width of the element to match the size of the image within

My webpage features an image along with some accompanying metadata that I want to be centered on the page. I want the div holding the metadata to be the same width as the image. Here's an example: Unfortunately, I am unable to determine the image&apo ...

How to position the navigation bar to the right using bootstrap

I have been experimenting with moving the navigation bar to the right side of the screen in bootstrap4 by using float: right; on the nav a element, but it doesn't seem to be having any effect. I am developing my project using a codepen app. Here is t ...

Is there a way to refresh a specific element without having to reload the entire page when the button is clicked

While working on a rock, paper, scissors game in JavaScript, I found it tedious to have to constantly reload the page after each play. To solve this issue, I attempted to add a button that would reset the game for a new round. However, I encountered an err ...

Creating a cascading layout with React Material-UI GridList

Can the React Material-UI library's GridList component be used in a layout similar to Pinterest's cascading style? I have utilized Material-UI Card components as children for the GridList: const cards = props.items.map((item) => <Card ...

The website shifts as you navigate to a new page

Could use some insight on an issue with my website . Whenever I navigate to a different page, like the "Rules" page from the main site, the container seems to shift down slightly. Any ideas on what could be causing this? I've been struggling to pinpoi ...

jQuery and CSS animation implemented on website performs flawlessly on all browsers, with the exception

I have recently started learning jQuery and I am facing an issue with the website linked below. It works perfectly in Firefox, Chrome, and Opera but not in Safari. <head> <meta charset="UTF-8"> <meta name="viewport" content="width=devic ...

Achieve centered alignment for a website with floated elements while displaying the complete container background color

I am currently working on a website that consists of the basic elements like Container, Header, Content, and Footer. The container has a background-color that should cover the entire content of the site, including the header, content, and footer. However, ...

I attempted to use jQuery to render a partial view within my main view, but for some reason, the partial view does not show up at runtime

In the controller, there are actions defined: public ActionResult AdminRoles(int? selectedValue) { if (!LogedUser.InRole(Functions.User, Roles.View)) return RedirectToAction("Login"); return View(db.Users.Where(u => u.I ...

The filter on the mobile version is not displaying correctly

When I select a category in the input filter, only items with the same category are displayed when clicked. However, when I click on "Others" on the desktop version, only rows with that category are shown, but on mobile after resizing and filtering, nothin ...

One XMLHTTPRequest with multiple replies

My requirement is to have a consolidated XMLHttpRequest call that returns three unique items. These items consist of an HTML formatted table and two separate sets of JSON data for Google Charts. The reason behind this design is that the chart data relies o ...