A technique for horizontally centering an image while simultaneously ensuring that the bottom is pushed down, even at an unknown resolution, and maintaining center alignment if

Imagine a scenario where I have an image with unknown resolution. My goal is to horizontally center it, even if the window's width is smaller than the picture, while also adjusting the bottom of the window to match the height of this picture.

Is there a way to achieve this using only css, without involving javascript?

The image will be placed within an <img> tag as it helps adjust the bottom. Center alignment itself is not difficult, but the challenge lies in keeping it centered similar to background-position:center top. The problem arises when simply centering the <img> tag causes it to hit the left border of the window instead of being hidden and remaining centered.

Appreciate any solutions you can provide. Thank you!

Answer №1

To achieve this effect using the img tag, you can utilize the following two codes:

object-fit:cover;
object-position:50% 50%;

These codes function similarly to background-size and background-position properties.

Here is an example of how it can be implemented in code:

html,body {
  width: 100%;
  height: 100%
}
img {
  width: 100%;
  max-width: 100%;
  max-height: 100%;
  object-fit: cover;
  object-position: 50% 50%;
  float:left;
}
div {
  width: 100%;
  height: 100%;
  background: #222;
  display:flex;
  color:#fff;
  align-items:center;
  justify-content:center;
}
<img src="https://www.rafaeldejongh.com/wp-content/uploads/2016/12/GlitchSkull1.jpg" alt="Rafael De Jongh - Glitch Skull"/>
<div>  
  <p>Other Content</p>
</div>

You can also view this implementation on JSFiddle

If you prefer a full fluid background image that covers 100% of the viewport's width and height, you can achieve that with the following code:

html,body {
  width:100%;
  height:100%
}
#img {
  width:100%;
  height:100%;
  max-width:100%;
  max-height:100%;
  background-image:url(https://www.rafaeldejongh.com/wp-content/uploads/2016/12/GlitchSkull1.jpg);
  background-size:cover;
  background-position:center center;
  background-repeat:no-repeat;
  float:left;
  display:inline-block;
}
#content {
  width:100%;
  height:100%;
  background: #222;
  display:flex;
  color:#fff;
  align-items:center;
  justify-content:center;
}
<div id="img"></div>
<div id="content"><p>Other Content</p></div>

Also available on JSFiddle

If you have any more questions, feel free to ask!

Answer №2

Check it out here: https://jsfiddle.net/gwga7h5y/

Here's the HTML code snippet:

<div id=myDiv>
    <div id=imageWrapper>
        <img src="https://upload.wikimedia.org/wikipedia/commons/9/94/Ingres%2C_Self-portrait.jpg" border=0>
    </div>
</div>

<p>
The image remains centered and doesn't overflow the window borders even if it's too narrow, with the text adjusting accordingly without needing to know the image height.
</p>

And here's the CSS code snippet:

html, body {
  width:100%;
  height:100%;
  text-align:center;
  overflow-x:hidden;
}

#myDiv {
  position:relative;
  left:50%; /* Positioned in the middle of the window */
  width:0;
  overflow-x:visible;
  text-align:center;
}

#imageWrapper {
  display:inline-block; /* Container width matches image width */
  position:relative;
  margin:0 auto 0 auto;
}

#imageWrapper img {
  display:block;
  position:relative;
  margin-left:-50%; /* Image pushed left by half its container width */
}

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 conceal a parent element with jquery?

Let's say we have the following HTML structure: <li class="fooli"> <a class="foo" href="javascript:foo(this);">anchor</a> </li> <li class="fooli"> <a class="foo" href="javascript:foo(this);">anchor</a> ...

Looking to retrieve the <td> element using the class name?

When a specific condition is met in the class name, I want to apply styles to an entire row. The table structure I am working with is as follows: <table> <tbody> <tr> <td><div><span class='level2'></span&g ...

The footer is supposed to be at the bottom, but unfortunately, the clear float isn

Today seems to be a rough one without enough coffee, as I'm struggling to remember how to do this I am trying to achieve the following layout: header content float float footer The content section contains two floating elements. The problem is ...

Can we dynamically add an identical DOM structure by clicking a button using jQuery?

I currently have ten text fields within a single div. I am interested in including another set of ten text fields with the same name, class, and id. Is there a way to recycle the existing DOM structure mentioned above, or will I need to generate and add t ...

Tips for integrating an HTML template into a React project

I'm finding it challenging to integrate an HTML template into React. The template I am using is for an admin dashboard with multiple pages. I have successfully copied and pasted the HTML code into JSX files and fixed any syntax issues. Here's wh ...

Text vanishing upon the loading of an HTML webpage

I am experiencing an issue where the text on my webpage disappears after it loads, and I am struggling to figure out the cause. (I did not create the site) The white text displayed on top of the header image initially appears correctly but then vanishes. ...

Managing numerous ajax forms within a single page

Upon receiving advice from the following inquiry Multiple forms in a page - loading error messages via ajax, I am endeavoring to incorporate multiple forms within one page. The goal is to insert error messages into the corresponding input div classes. I pr ...

Tips for ensuring Marketo forms are responsive when integrated into a WordPress website

We are currently using Wordpress for our responsive website. Within the site, we have integrated Marketo forms (a marketing automation system) with custom CSS for styling. The issue we are facing is that while the forms appear fine on desktops, they cause ...

Dropdown menu is not positioning correctly over other elements on the webpage

After researching multiple stack overflow questions and attempting various solutions, I still haven't been able to resolve my issue. Please refrain from marking this question as a duplicate. The problem I am facing is that my dropdown menu is not ap ...

When it comes to using jQuery, I find that it only functions properly when I manually input the code into the Google Chrome console. Otherwise

Below is the HTML snippet: <textarea cols="5" disabled id="textareRSAKeypair"> @Model["keypair"] </textarea> <a href="#" class="btn btn-primary" id="downloadKeypair">Download Key</a> Here is the jQuery code: <script src="ht ...

Perform Jquery trigger on mobile by clicking, and on desktop by hovering

Despite encountering this question numerous times, I am still unable to find a solution. I have a dropdown menu and I want it to open on hover for desktop and on click for mobile devices. I attempted using the provided code, however, it only works after r ...

What is the best way to parse a JSON file and create a dynamic webpage using jQuery with the data from the

As someone who is new to working with Node.js and JSON, I am encountering some issues when trying to extract data from a JSON file. Below is the code that I have written: 'use strict'; const fs = require('fs'); let questsRawData = fs ...

"Combining HTML, PHP, and JavaScript for Dynamic Web

Here is the PHP function that retrieves the visitor's profile image thumbnail: <?php echo voip_profile_image($visitorid,'thumb'); ?> The issue lies in the fact that $visitorid is stored in JavaScript under the sRemoteid parameter. Wi ...

I am having trouble scrolling through the main content when the side-drawer is open. How can I fix this issue?

When the sidebar is opened, I am facing issues with the main content scroll and certain fields such as select options and search bar not functioning properly. I have included the main content in the routes from which it is being loaded. However, the scroll ...

What is the best way to create a sign-up box that appears on the same page when you click on the sign-up button

I am interested in implementing a 'sign up' box overlay at the center of my index page for new users who do not have an account. I would like them to be able to easily sign up by clicking on the 'sign up' button. Once they complete the ...

Encountering issues with accessing image files located in the public folder of my Next.js project - Receiving a 404 Error message

I am currently facing an issue with my Next.js project where I am unable to use image files from the public folder. Despite checking that the file paths, names, and extensions are correct, as well as ensuring my configurations are accurate, I keep encounte ...

Tips for preventing delays in the digest cycle caused by two-way binding

When does two way data binding get triggered in AngularJS? In my AngularJS application, there is a parent directive and a child directive. Parent Directive: angular .module('myApp') .directive('customForm', function(customService ...

Expanding an element to cover all columns in a grid with automatically generated columns

I am working on a CSS grid layout with automatic columns and 2 rows. All elements are normally placed in the first row except for one special element that should span both rows while filling all available column space. My current code looks like this: ...

Guide to easily printing a page in Angular 4 using TypeScript

When using my web app, there are certain pages where I need to print only a specific component without including the sidebar. I have written the following TypeScript code to achieve this: print() { window.print(); } The relevant HTML code begins with: & ...

When setting the form action attribute in jQuery, the parameter being passed may be null

My goal is to redirect my form action to another page with a URL parameter. Here's the code I'm using: ui.setFormActionToTargetPage = function () { $('form').get(0).setAttribute('action', 'myTargetPage.html?id=' ...