Dynamically setting CSS values with jQuery to center an image within a div

I'm trying to center an image in a div according to the width of the image after I scale it to have a height of 250px.

For example, if I had an image with dimensions 625x450 and, in my CSS file, set the height of the image to be 250px, then the width would automatically scale to 347.22px. I want to be able to detect that scaled width and then set a margin-left of (width - height)/2 to center the image.

The CSS for this example in hard-coded form would look like this (the entire fiddle is here):

.gallery {
    width: 250px;
    overflow: hidden;
    position: relative;
}

.gallery img {
    height: 250px;
    width: auto;
    margin-left: -48px;
}

But I want to be able to do this on the fly with images of other dimensions. I have attempted to do this by cutting out the margin-left line of the hard-coded CSS and adding some jQuery (the entire fiddle is here):

$(document).ready(function(){
    oldWidth = $('.gallery img').width();
    newMarg = (oldWidth - 250)/2);       
    $('.gallery img').css("margin-left", newMarg);
}

I have not had any success with that approach, though. It has to be something with the jQuery that I'm messing up. I'm very new to everything I'm attempting to do here, and I feel like I might be missing something simple.

Answer №1

After reading through this informative thread

I applied the suggested changes from that discussion to your jsFiddle:

Modified jsFiddle

<div class="outer">
   <div class="inner">
       <img src="" />
   </div>
</div>

and

.outer {
  width: 250px; overflow: hidden;
}
.inner {
  float: left; position: relative; left: 50%;
}
.inner img {
  height: 250px; display: block; position: relative; left: -50%;
}

The great part about this solution is that it does not rely on Javascript

Answer №2

To center the image on the page, set display:block and apply margin: 0 auto;text-align:center;

Answer №3

Aside from some errors in parentheses placement, the subtraction was actually done in reverse order:

$(document).ready(function() {
    oldWidth = $('.gallery img').width();
    newMarg = (250 - oldWidth) / 2;
    $('.gallery img').css("margin-left", newMarg);
});​

http://jsfiddle.net/99PMd/10/

Please take into consideration that if there are multiple .gallery or img elements within it, the variable oldWidth will only capture the width of the first image found in the DOM. If you have multiple images or galleries, you should consider refactoring your code with a loop:

$(document).ready(function() {
    $('.gallery img').each(function() {
        oldWidth = $(this).width();
        newMarg = (250 - oldWidth) / 2;
        $(this).css("margin-left", newMarg);
    });
});​

http://jsfiddle.net/99PMd/11/

Personally, I believe overflowing an image like that is not visually appealing, so resizing the image to fit its container would be a better option. This can be achieved using pure CSS:

.gallery img {
    height: auto;
    max-width:100%;
}​

http://jsfiddle.net/99PMd/12/

Answer №4

CodePen

$(document).ready(function(){

   var containerWidth = 300;
   var imageWidth = $('.image-container img').width();

   if(imageWidth > containerWidth){
       $('.image-container img').css({marginLeft: (containerWidth - imageWidth)/2 });
   }

});

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 method to ensure a TALL table header is repeated on every page in Chrome?

First time poster =) I am currently facing an issue while trying to print a long table and have the table header repeat on each page. The problem arises when the height of the <thead> reaches a certain threshold, specifically 242px in Chrome 87.0.42 ...

How to utilize a specific option as a variable within a PHP select dropdown menu

In my PHP code, I am retrieving data from an Azure SQL database and using it to populate a drop-down menu with options. The SQL query I used returns two columns: Title and Cycle_ID. After setting the Title as the text string and Cycle_ID as the value for ...

Angular 5: Using JQuery Datatable row.add with button click functionality

I recently started using jquery datatable within my angular 5 project and am encountering an issue with adding dynamic rows. addNewrow() { this.dataTable.row.add([<button onclick="myFun()" name="btn1">btn</button>,1,2,3]).draw(true); } ...

Fill in a data table beginning with the column next to the first

My issue involves a datatable retrieving JSON data from an API. The table is configured so that the first column should only display a checkbox. However, upon data retrieval, the first column gets populated as well. https://i.sstatic.net/izb5B.png $.getJ ...

Receiving an error message stating "The JSON value could not be converted to System.Int32" when attempting to post JSON data via AJAX to a Web API

I need to transfer information from my website to a WEB API that my partners are developing via AJAX. This WEB API is built on a .net Core 3.0 application, and the purpose is to register new users. However, I am encountering an issue with parsing the inpu ...

Unlocking the Magic of JSONP: A Comprehensive Guide

Currently attempting to utilize JSONP in order to work around Cross Domain challenges. I referenced this solution: Basic example of using .ajax() with JSONP? $.getJSON("http://example.com/something.json?callback=?", function(result){ //response data a ...

How to Toggle a RequiredFieldValidator on/off with a Checkbox in ASP.NET using C#.NET and jQuery/JavaScript

I am facing an issue with enabling or disabling a required field validator based on the checkbox status. The goal is to have the validator enabled when the checkbox is checked and disabled when it is unchecked. Additionally, when the checkbox is checked, a ...

Issue with preventdefault() function in Internet Explorer 8

I've encountered a problem while working on a page that heavily utilizes ajax. Everything seems to be functioning well across different browsers, except for one final step that is broken in IE8 and below. You can view the issue on this demo page: To ...

Tips on moving the first item on the Bootstrap navigation bar to the left side

I have successfully implemented a Bootstrap navigation bar and created a container to display some descriptive text beneath it, as depicted in the image provided. Utilizing the most up-to-date version of Bootstrap has ensured smooth integration. https://i ...

Adjust the dimensions of a Three.js generated 3D cube dynamically during execution

Is it possible to dynamically change the dimensions (width/height/length) of a 3D Cube created with Three.js? For example, I found a Fiddle on Stack Overflow that changes the color of a Cube at runtime: http://jsfiddle.net/mpXrv/1/ Similarly, can we modi ...

What is the most efficient way to substitute text within an HTML document?

Is there a way to switch between languages on a website to replace text on multiple pages with a simple button click? What is the most efficient method for achieving this? This code snippet only changes text in the first div. Is there a way to implement a ...

Ways to deactivate the Bootstrap collapse feature

In my accordion FAQs, I am facing an issue where Question 1 is automatically opened when the page loads. Additionally, when I click on Question 2, it closes instead of staying open. I would like to address these problems and make sure that each question st ...

JavaScript not functioning properly with HTML loaded via .load()

I'm facing a perplexing dilemma: My issue revolves around this JS code: EDIT updated JS $(".img-thumb").on("click", function(){ // displaying the same behavior as .click() thumbID = $(this).attr("id"); console.log(thumbID); $(".gal-act" ...

The .val() method is compatible with input fields, but does not work

Having trouble retrieving the value from a textarea input. Switched to an input field and it's working fine. Note: The issue seems to be related to tinyMCE. Removing tinyMCE allows the code to work properly. Any thoughts on this? $('.answer ...

Css styling for text highlighting

It's been some time since I encountered a CSS problem, but here I am facing one. In short, I want to highlight text with a gradient background, which I managed to achieve using the <span> tag and setting a background image on it. However, I ran ...

Discover the best way to integrate your checkbox with your Jquery capabilities!

I am having trouble getting my 3 checkboxes to interact with the JQuery button I created. The goal is for the user to be able to select an option, and when the button is clicked, the selected options should download as a CSV file from my feeds. Below is th ...

Is the presence of hidden list items leading to excessive white space?

I have a menu that appears when hovering over a list item. Here is an example: <li> <ul class="topmenu"> <li class="submenu"> <a class="otherIT" href="#" title="Common IT Tasks"><img src="./images/ittasks.png" alt= ...

Exploring the dynamic world of Angular2 animations paired with the

In my layout, I have a row with three columns and two buttons to toggle the visibility of the side panels: col-md-3 col-md-7 col-md-2 ------------------------------------ | | | | | left | middle panel | | ...

Eliminate redundant sets of comma-separated numbers from the jQuery input text value

On my webpage, there is an input with a value that looks like this: 1,7,1,4,22,58,58,1,1,4,7 <input type="text" name="hello" id="thankyouforhelping" value="" aria-invalid="false"> I have attempted mu ...

Tool that closely mirrors the functionalities of Google Maps

Seeking to develop an interactive image feature on my website akin to Google Maps but with custom images. Desiring functionalities like drag, scroll, and zoom in/out for enhanced user experience. Interested in any suggested tools or plugins for this purp ...