Center and align the background image in the middle of the page

Below is the provided html code snippet:

<div class="gallerybox">
<a href="/CustomContentRetrieve.aspx?ID=398791">
<img alt="" src="/Utilities/image.jpg" width="400" height="400" />
</a>
</div>

Here's the corresponding css code:

.gallerybox {width:200px;height:200px;overflow:hidden;}

Could someone suggest a method to center the linked image inside the div.gallerybox both vertically and horizontally? This could potentially involve using javascript, jQuery, or plain css.

Answer №1

Perhaps you could try something along these lines:

<div class="gallerybox"> 
  <a href="/CustomContentRetrieve.aspx?ID=398791"> 
    <img id="imgUtility" class="galleryImage" alt="" src="/Utilities/ShowThumbnail.aspx?USM=1&amp;W=400&amp;H=400&amp;R=1&amp;Img={tag_image_value}" />"  /> 
  </a> 
</div> 

.gallerybox {
  width:200px;
  height:200px;
  overflow:hidden;
}

<!-- Make Changes Here -->
<script language="javascript">
window.onload = adjustImage;

function adjustImage() {
  var img = document.getElementById('imgUtility');
  var x = img.offsetWidth;
  var y = img.offsetHeight;

  img.style.left = -(x / 2);
  img.style.top = -(y / 2);
}
</script>

Answer №2

Hey Jackson! I have a suggestion for you that involves some HTML rewriting, which might be the most effective solution for your issue.

You can start by creating a hidden image with encoded database info using <img>:

img#imgUtility {
   display: none;
}

(CSS and HTML)

<img id="imgUtility" class="galleryImage" alt=""
src="/Utilities/ShowThumbnail.aspx?USM=1&amp;W=350&amp;H=350&amp;
R=1&amp;Img={tag_image_value}" />

After the page loads and the image's URL is resolved, you can replace the <img> with a <span> in your HTML and set the hidden tag's src as the background image of the <span> using JavaScript:

// Make sure galleryBoxLinkTarget refers to the <a> inside div.galleryBox
function imgReplacement(galleryBoxLinkTarget) {
   var span = document.createElement("span");
   var img = document.getElementById("imgUtility");
   span.style.backgroundImage = "url('" + img.getAttribute("src") + "')";
   span.className = "imgReplacement";
   galleryBoxLinkTarget.appendChild(span);
}

(JavaScript and HTML)

<div class="gallerybox">
   <a href="/CustomContentRetrieve.aspx?ID=398791">
      <!-- <span> goes here -->
   </a>
</div>

Finally, add some CSS magic:

span.imgReplacement {
   display: block;
   background-position: 50% 50%;
   background-repeat: no-repeat;
   width: 200px;
   height: 200px;
}

This method will center the picture regardless of dimension and allow you to remove inline width and height. Happy coding!

Answer №3

Give this a shot:

<style type="text/css>
  .gallerybox {text-align:center;vertical-align:middle;height:400px;line-height:400px;}
  .gallerbox img {display:inline; vertical-align:middle;}
</style>

<div class="gallerybox">
   <a href="/CustomContentRetrieve.aspx?ID=398791">
   <img alt="" src="/Utilities/image.jpg" />
</a>

Answer №4

Here's a neat little trick using a custom JQuery function named center:

     jQuery.fn.center = function() {
        this.css("position","absolute");
        this.css("top", (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px");
        this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px");
        this.css("bottom", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px");
        return this;
      }
    $(document).ready(function(){
$(#imgUtility).center();
)};

Implementing this with the given HTML structure:

<div class="gallerybox"> 
  <a href="/CustomContentRetrieve.aspx?ID=398791"> 
    <img id="imgUtility" class="galleryImage" alt="" src="/Utilities/ShowThumbnail.aspx?USM=1&amp;W=400&amp;H=400&amp;R=1&amp;Img={tag_image_value}" />"  />  
  </a> 
</div> 

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

Consolidate two AJAX requests into a single callback

I'm developing a Chrome extension and facing the challenge of merging two separate AJAX calls into one callback upon success. What would be the most efficient approach to achieve this? Auth.prototype.updateContact = function(id, contact_obj) { var ...

We were unable to locate the module: Unable to locate './components/counter' in 'C:/...democounter-appsrc'

I'm completely new to React and currently following tutorials by MOSH on YouTube. However, I've encountered an error that I can't seem to resolve even after searching for similar questions. index.js import React from 'react'; imp ...

Should I wait for my state to be updated with new information before triggering the render function?

Can someone assist me with restructuring the code below to ensure that the information in the data array is displayed on the initial page load? async componentDidMount() { const { id } = this.props.match.params const soccerApi = axio ...

Sophisticated solution for bridging the space between the div edge and its contents

When examining this specific fiddle, a 1px gap is noticed between the background of the links and the background of the #content div in various browsers, even when zoomed at different levels (the reason for this zoom effect remains unknown). This issue see ...

The issue arises when the mat-panel-description is not properly aligned with the shrinking panel

Within my HTML, I have a mat-panel with a description that is populated by a variable from the TS file. However, I am encountering an issue where if I shrink the panel and the description is too long, the text is cut off at the top and bottom. Is there a w ...

Having trouble choosing an option from the angular dropdown list with Protractor

I attempted to choose the second item from an Angular drop-down menu, but the webdriver couldn't locate this element. Error: The WebDriver encountered a NoSuchElementError when trying to find an element using the locator By.cssSelector("[ng-click=&b ...

What is preventing me from viewing my cards in flex or grid layout?

Recently, I created cards for my team members, but encountered layout issues despite using CSS Flexbox and CSS3 Grid. Although both are supported by my browser, the problem persists. However, the layout works perfectly on mobile devices! I experimented wi ...

Can anyone advise me on the best way to showcase PHP output using Jquery?

Exploring the world of jQuery and Ajax, I find myself in need of assistance with displaying PHP output data using jQuery. Here's a snippet from my html file: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR ...

Having trouble with the "next" pagination button not loading cards, even though the numbered buttons are working perfectly

My pagination numbers are functioning correctly, but I'm having trouble with my "next" or "previous" buttons. I am using Bootstrap 5 and jQuery to load cards from an array. The issue seems to be with the currentPage variable in my displayList function ...

In what way can a button be made clickable just one time?

I have a dilemma in my code where I need a button to be clickable only once. To solve this problem, I created two buttons and disabled one of them after the user clicks on either button. <div style = "position:absolute; left:625px; top:100px; bac ...

What could be causing the sporadic functionality of my jQuery image resizing code?

Seeking help for an issue I am facing with my jQuery code. I have been trying to scale a group of images proportionally within an image carousel using jCarousel Lite plugin. However, the resizing code seems to work randomly and I can't figure out why. ...

Organize Grid items in a column using Material UI and React

Seeking assistance with adjusting the positioning of my Grid Items in Material UI. Progress so far can be found on Codesandbox. The issue at hand is how to align items 2 & 3 to the right of item 1. I've made some progress but struggling with str ...

Why won't the glyph-icons appear on my navigation bar in Bootstrap?

I'm currently designing a navigation bar for my website. HTML <nav class="navbar fixed-top navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" d ...

Adaptable Layouts in Bootsrap Grid

I am currently working with Bootstrap Grid. https://i.sstatic.net/giJOI.png One issue I am facing is when I switch back to my mobile screen, I want the layout to adjust accordingly like https://i.sstatic.net/RYPJm.png I have tried different methods but ...

What is the best way to align a value within CardActions in Material UI?

I'm currently facing an issue with my website design. Here's a snapshot of how it looks: https://i.sstatic.net/UuBJJ.png Additionally, here is the code snippet related to the problem: <CardActions> <Typography style={{ fon ...

styling a flex container with aligned text and buttons

I'm attempting to align text on the left and button controls on the right within a display: flex div. <CustomFieldContainer> <StyledWellContainer> <FieldDetails key={id}> <H4 bold>{label}</H4> <Styled ...

Creating a unique layout with CSS: layered divs

I'm struggling with a stubborn layout issue that I just can't seem to figure out... - Left column - Fixed, Static (always in view) - Right column - Fluid/liquid/scrollable --- Header - fixed --- left/main fluid/liquid --- Right/sidebar - fixed ...

The issue occurs when using z-index: -1 in Google Chrome causes links to malfunction

Recently, I encountered an issue with Chrome. When I applied a z-index of -1 to a position: relative; unordered list, the links within it became unclickable. You can see an example at http://jsfiddle.net/raLnx/ using Chrome 20.0.1132.47m. There is no pro ...

Bootstrap grid. Instead of moving to the next row, scroll horizontally when the content overflows

Here is the code snippet: <div class="row shochatgroup"> <div *ngFor="let message of messages" class="col-auto"> <button *ngIf="message.state.attributes.shochatpaid > 0 && message.state.at ...

Guide to applying external styles to sub-components in Material UI while maintaining a cohesive common style throughout the entire component

I have a main page that consists of various smaller components. Within the page folder, there is the main page file, an external styles file, and folders for each individual sub-component - each of which has its own unique style. I'm struggling to fi ...