aligning an image in the center of a webpage

I have created a simple HTML code to center an image inside the body of an HTML page. It works perfectly on Windows with various browsers, and on phones vertically when rotated. However, the issue arises when I open the site on a Mac as the centering does not work with all browsers. Here is the code snippet:

<!DOCTYPE html>
<html lang="en">

<head>
    <link rel="icon" href="img/icon.png">
    <title>LaBera</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="includes/bootstrap-3.3.5-dist/css/bootstrap.min.css">
    <script type="text/javascript" src="includes/jquery-1.11.3.js"></script>
    <script src="includes/bootstrap-3.3.5-dist/js/bootstrap.min.js"></script>
    <style>
        html {
            height: 100%;
            position: relative;
        }
        body {
            background-image: url("img/pattern-small.png");
            background-repeat: repeat-x-y;
            height: 100%;
            overflow: hidden;
            position: relative;
        }
        .centerimg {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translateX(-50%) translateY(-50%);
        }
    </style>
</head>

<body>
    <div class="container ">
        <div class="centerimg">
            <img src="img/logo1300.gif" class="img-responsive" alt="Logo" width="241px" height="400px">
        </div>
    </div>
    <footer class="footer navbar-fixed-bottom">
        <img src="img/footerNoShadow.gif" class="img-responsive" alt="Footer" height="66px">
    </footer>
</body>

</html>

Answer №1

Take a look at this solution:

<style>
html {
  height: 100%;
  position: relative;
}

body {
  background-image: url("img/pattern-small.png");
  background-repeat: repeat-x-y;
  height: 100%;
  overflow: hidden;
  position: relative;
}

.centerimg {
  position: absolute;
  top: 50%;
  left: 50%;
  -ms-transform: translate(-50%, -50%); /* IE 9 */
  -webkit-transform: translate(-50%, -50%); /* Chrome, Safari, Opera */
  transform: translate(-50%, -50%);
}
</style>

Be sure to notice the adjustments made to the transform property. The additional prefixes are included for better browser compatibility which may help resolve your issue.

https://i.sstatic.net/xT7Bp.png

Answer №2

If you want to center an image within a container, consider using the table/table-cell method.

To start, make sure the parent element (which could be the body in this case) has its display property set to table. Remember to specify the dimensions explicitly because tables only occupy as much space as their content by default.

Next, the child element (the image in this scenario) should have the following styles applied:

display: table-cell; vertical-align: middle;

Putting it all together:

.parent {
  display: table;
  width: 100%; // adjust as needed
  height: 100%; // adjust as needed
}

.child {
  display: table-cell;
  vertical-align:middle;
  max-width: 100% // ensures the image stays within its parent and remains responsive
}

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

What is the best way to implement colorful opening hours in code?

I found this code on a different platform and decided to tweak it to display only Monday - Friday, Saturday, and Sunday. However, I'm stuck trying to update the Javascript code to match my modifications. Any help would be appreciated! You can view th ...

Can the navbar brand be centered in Bootstrap 4 while also aligning some text to the left of the brand?

Just dipping my toes into website coding and Bootstrap is a whole new territory for me. I'm struggling with centering the brand in the navbar while keeping the text aligned to the left of it. So far, every attempt results in both elements being center ...

Trouble with Sound during Quickblox Webrtc Audio Calls

I am having an issue with my audio calls. When I make a call to another user, everything seems fine except that I cannot hear any sound when speaking into the microphone. I am only interested in making audio calls. The call is initiated by pressing a butt ...

Issues have been identified with the functionality of jQuery validation in MVC when applied to dynamically added elements

Although this issue has been addressed multiple times before, I am struggling to resolve it using the provided solutions. I am currently developing a basic library application. One of the features involves adding a copy of a book, which utilizes jQuery to ...

Highlight text when the user is scrolling the page - using JQUERY

Can anyone suggest a way to dynamically underline text as the user scrolls down a webpage? The underline should only be visible while the user is scrolling. I've experimented with animate.css and other plugins, but haven't been able to achieve th ...

I've encountered the error of receiving a __PHP_Incomplete_Class Object when attempting to create a session using jQuery-ajax

I have defined a new class named FinalResult class FinalResult { var $ReuestAnswer = null; var $givenAnswer = null; var $questionScore = 0; function setScore() { } function getScore() { return $this->question ...

Every time a new message is sent or received, I am automatically brought back to the top of the screen on the

I'm currently working on integrating a chat feature into my Angular Firestore and Firebase app. Everything seems to be functioning well, except for one issue - whenever a new message is sent or received, the screen automatically scrolls up and gets st ...

What is preventing hover from working correctly?

I'm having trouble getting images to display when hovering over text. Can anyone offer suggestions on what might be causing this issue? The images are being downloaded when clicked, so I know they're in the correct path. I've checked for com ...

Modifying Characteristics of Elements Added Dynamically

How do I change the type attribute for dynamically added buttons? In the code below, the label names are changing perfectly, but when I try to change button types, it applies to all dynamically added buttons. My requirement is to change every button type t ...

I am currently working with CakePHP and am interested in learning how to expire the admin session

I'm having issues with the code in my UserController. When I open the admin panel in two tabs within the same browser and log out from one tab, I am unable to redirect to the login page from the other tab when clicking on any menu. function beforeFil ...

Pressing the button will add text into the input field

Below is a jsfiddle link showcasing the current issue I am trying to address: http://jsfiddle.net/YD6PL/61/ Here is the HTML code snippet: <input type="text> <input type="text> <input type="text> <div> <button class="buttons"& ...

Prevent the cursor from exiting the div element when the tab key is pressed

Currently, I have implemented a search input box allowing users to either enter a value or select from a list of suggestions. The issue arises when the user selects an option using the tab key, as it causes the cursor to move outside the input box despite ...

Access an HTML element and using JavaScript to make changes to it

As a new web developer, I am eager to create a grid of file upload zones on my site. I have decided to use DropZone.js for this project. I have customized DropZone and added multiple drop zones in the HTML. The grid layout consists of four rows with four ...

Encountering an issue... invariant.js:42 Error: A `string` value was received instead of a function for the `onClick` listener

Currently, I am working on creating a form that allows users to build quizzes without any restrictions on the number of questions they must include. To achieve this, I plan to add an "add question" button at the bottom of the quiz form, allowing users to d ...

Using Bootstrap 5 to beautifully wrap an even quantity of boxes

My challenge is to optimize the spacing between 4 boxes based on screen size: The layout should adjust as follows: If it's xxl or larger, all 4 boxes should be in a single horizontal row. If it's md or larger, two boxes should be in the firs ...

Tips for enhancing the responsiveness of a calendar table in Bootstrap 5.2

Hello there! I need some help with adding rounded borders to tables using Bootstrap. Can anyone assist me with this? I'd be truly grateful for any guidance on this matter. Unfortunately, Stack Overflow is not allowing me to post my question, so I&apos ...

When the open button is clicked, the Div will toggle between open and closed states

Recently, some of my questions have not been well-received, which makes me feel a bit disheartened. It's important to remember to be kind when providing feedback. I've noticed that some people downvote without offering constructive criticism, whi ...

The jQuery error message "e.nodeName is undefined" indicates a timeout issue

<script type="text/javascript"> var delayFunction = (function() { var timer = 0; return function(callback, ms) { clearTimeout(timer); timer = setTimeout(callback, ms); }; })(); $(function() { $('#act ...

Switching the horizontal tab design from Bootstrap 3 to Bootstrap 4

I'm currently working on adapting a code snippet from bootsnip that creates horizontal Bootstrap tabs with material-style design. I've encountered some challenges in converting it to Bootstrap 4, specifically in updating the CSS to use .nav-item ...

What is the method for obtaining the total number of steps taken in a day (pedometer) exclusively for the current day on the

Is there a way to retrieve the total steps count for the current day only? The tizen.humanactivitymonitor.setAccumulativePedometerListener function allows me to access the accumulativeTotalStepCount, which represents the cumulative walking and running ste ...