Using jQuery to load the center HTML element

So here's the plan:
I wanted to create a simple static website with responsive images that load based on the browser width. I followed some suggestions from this link, but unfortunately, it didn't work for me. I tried all the answers and even attempted to change the CSS properties manually using:

$('.headerImg').css('margin','auto');  

I also explored other ideas from the provided link, but it seems like my image just won't center properly. The test image displays correctly according to screen width, without any conflicting definitions in my CSS file. If anyone has a solution or clue, I would really appreciate it...

Here's a snippet of my code:

 <html>
    <head>
        <title>broken</title>
        <!--styling-->
        <link rel="stylesheet" type="/styling/" href="styles.css">
    </head>

    <body>
    <!-- Scripts-->
        <script src="scripts/jquery-3.2.1.min.js"></script>
        <script type="text/javascript" src="scripts/constants.js"></script>
        <!-- fetch and store screen sizes-->
        <script type="text/javascript">
            localStorage.setItem("windowWith", screen.width);
            localStorage.setItem("windowHeight", screen.height);
            localStorage.setItem("imageSize", getImageSize());
        </script>

        <!--Header-->
        <div class="header">
            <script type="text/javascript">
            var path = "media/img/header_" + localStorage.getItem("imageSize") + ".jpg";
            $(document).ready(function() {
                $('.headerImg').attr("src", path);
            });
            </script>
            <img class="headerImg"></img>
            <br>
            <div class="menuItems"></div>
        </div>
        <!--Middle-->
        <div class="middle"></div>
        <!--Footer-->
        <div class="footer"></div>
    </body>
</html>

Lastly, here's the JavaScript file used for determining which picture size to pick:

//const enum to define where 
var width = {
    large:1280,
    medium:800,
    small:460,
    xsmall:330
};

//sets the size for the header image
function getImageSize(){
    var size = "";
    var screenWidth = localStorage.getItem("windowWith");
    if(screenWidth >  width.medium){
        console.log("loading large picture");
        size = "large";
    }
    else if(screenWidth <= width.medium && screenWidth > width.small){
        console.log("loading medium picture");
        size = "medium";
    }
    else if(screenWidth <= width.small && screenWidth > width.xsmall){
        console.log("loading small picture");
        size = "small";
    }
    else if(screenWidth < width.small){
        console.log("loading xsmall picture");
        size = "xsmall";
    }
    if(size == ""){
        size = "xsmall";
        console.log("Error - screen size not found - loading xsmall header");
    }
    return size;
}

Answer №1

Image tags are inline elements, which cannot be centered using "margin: 0 auto;"

To center the image, you should make it a block element by adding "display: block;"

Here is an example of how your CSS should look:

.image-center {
    display: block;
    margin:  0 auto; 
}

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

Position the DIVs at the bottom of the TD

I'm having trouble aligning two DIVs within a table TD to the bottom of the table. Despite trying various alignment methods, the left DIV simply won't move. It's crucial for me to design this email responsively, ensuring it still displays co ...

Function anomalies triggered by delayed setState updates with React Hooks

Creating a Quiz app with React involves fetching questions as an array and managing the following states: An array containing all question details - statement, options, chosen answer, status (answered, marked for review, unvisited); An object holding info ...

Preventing div elements from being highlighted when double-clicked

I'm working with a div element that has a background image and I need help figuring out how to disable the highlighting effect when double-clicking on it. Is there a CSS property that can achieve this? ...

When attempting to retrieve data in a server-side component, Next.js encountered an ECONNREFUSED error with ::1:3000

import React from "react"; import axios from "axios"; interface UsersType { id: string; firstName: string; lastName: string; email: string; } interface dataProps { allUsers: UsersType[]; } async function getData() { try { c ...

Is it common in Node.js to create multiple instances of "server" objects, but only connect one to a port?

After finishing "Node.js in Action", I'm now piecing together the concepts of Node.js, Connect, and Express. My inquiry revolves around the creation of servers in Node. node_server = http.createServer(); connect_app = Connect(); express_app = Express ...

The error message "TypeError: Unable to access property of undefined when using web sockets"

Exploring Isomorphic framework for React and integrating Pusher for websockets communication. I'm encountering difficulty accessing the state within the componentDidMount() function. class TopbarNotification extends Component { state = { vis ...

Ways to retrieve an isolated scope in a directive without utilizing a template

It is clear that when I assign a controller to an element, the element along with its children can access the controller's scope. However, it is surprising that when I include a directive with an isolated scope on an element (as an attribute), I woul ...

An error occurs when attempting to use Socket.io without explicitly returning the index.html file

I want to implement WebSockets without needing to return the index.html file. As someone new to Socket.IO, here's what I've attempted: First, I installed Socket.IO using npm: npm install socket.io --save Then, I created a file called index.js ...

Using jQuery to assign the value of a hidden element to data being posted

When using jQuery's post() method to call an ajax action that returns JSON data ({"Success": "true" } or {"Success": "false"}), the value of a hidden HTML element is supposed to be set to the Success value in the returned object. However, after settin ...

Issue: The 'loopback' module is not found in the NodeJS environment

I can't seem to solve the issue I'm experiencing. Error: Module 'loopback' not found These are the dependencies listed in my package.json file: "loopback": "^3.19.0", "loopback-boot": "^2.6.5", "loopback-component-explorer": "^6.0. ...

Creating an account form using PHP and MySQL

All fields in my registration form are working properly except for the village field, which is returning a '0' in the database. To enhance user experience, I implemented AJAX and jQuery to create dropdown lists for governorate, district, and vil ...

Showing text above bars in MUI X BarChart

I am currently utilizing the <BarChart> component from @mui/x-charts (version "^6.19.1") and I am looking to enhance readability by displaying the data values on top of each bar. Current Output: view image description here Desired Outc ...

Activate the 'li' element within the 'ul' whenever a 'ui-sref' link on the

I have been working on building a dashboard that consists of an abstract state called dashboard, with subdashboard as the immediate child state. Previously, clicking on user details would take the user to the dashboard.tables state. However, I encountered ...

Displaying or hiding table columns in Vue.js Element-UI el-table based on screen width: a step-by-step guide

Here is my code snippet for generating a table: <el-table :data="tableData" empty-text="No data to display :( " v-if="window.width > 855"> <el-table-column v-for="column in tableColumnsMd" :key=&q ...

Instructions for creating a background within a container and positioning text in the center of the image utilizing HTML and CSS

I am currently learning HTML, CSS, and JavaScript. I am in the process of building my very first website, but I have encountered a problem. I am struggling to change the background color within the container beneath the images to a specific color (#82b5cf) ...

Button with small width containing an icon and text

I am trying to create a simple HTML button that has an icon on top and a description below it. <div class="mybtn"> <div><img src="someimage.png"></div> <div>Button description</div> </div> My question is, ...

Encounter issue when attempting to insert multiple items into MongoDB

// Import User and Item Models const User = require('../../models/User'); const Item = require('../../models/Item'); router .post('/login/:id', passport.authenticate('jwt', {session: false}), (req, res) => { ...

Tips for setting up personalized breakpoints for a Bootstrap navbar

I am currently facing an issue with my navbar on tablet view. Despite implementing custom breakpoints to collapse the navbar at 1050, the menu bar is appearing in two rows instead of one. I have tried using the code below but it doesn't seem to be wor ...

Unusual CSS anomalies encountered on iPhone devices

Having an issue with the animation on my homepage where the logo spins into place. It works fine on desktop and in Chrome and Firefox mobile simulators, but on actual phones it rotates an additional 90 degrees. Included are screenshots from the Firefox mob ...

I feel like I'm stuck in a never-ending loop of COR issues that are blocking my progress on

My main focus is establishing a direct connection between a computer and a Raspberry Pi within a local network. It's important to clarify that this project will never have any connection to the internet. The Raspberry Pi is running a NodeJS server th ...