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

Endless scrolling feature malfunctioning

On my profile_page.php, the default setting is to display 10 posts (10 rows from the database) for the user. If a user has more than 10 posts, and scrolls to the bottom of the page, the div should expand to reveal the remaining posts (maximum of 10). For e ...

Send the form embedded in an iframe to a separate window

I have a form embedded in an iframe, but I'm looking to open the submitted form in a new window. What would be the best way to achieve this? ...

An unforeseen issue occurred while trying to access an indexed element ID

I've recently started learning javascript and jquery, and encountered a problem while working on a script. The script is created by php code that reads lines from a file, processes them, and displays them using arrays. In addition, javascript validat ...

I am experiencing issues with the interpolation of my SASS variables when they are placed into

I am relatively new to the Nuxt ecosystem and I must say it's an awesome package that really simplifies our lives. Currently, I am attempting to incorporate sass into my project. Despite following the steps outlined in the documentation, my build is ...

Unable to assign unique identifiers to elements within a user interface framework

I am having difficulty assigning an id to components. Scenario 1: - Trying to assign an id to an HTML component. <h1 id="demo-h1">Demo Heading</h1> Assigning id to HTML component Scenario 2: - Attempting to assign an id to a componen ...

Body of the table spanning the entire width of the screen

Looking for a solution to create a responsive table layout where the thead stretches up to a specified div, while the tbody expands to fill the entire screen width. Is this achievable without using fixed values? https://i.stack.imgur.com/v2ZYx.png It is ...

Ensuring a dependable detection of WebSocket connection status

I've been researching how to create a dependable method for recovering a WebSocket connection. After exploring various options, I discovered that one approach involves sending heartbeats (ping/pong) to the server and monitoring if the entire pong is ...

Click Function for Modifying the Content of a Popup Window

I'm a beginner in JavaScript and I need help figuring out how to achieve the following task. Essentially, my goal is to have lines of code like this: <a onclick="JavascriptFunction(0000000)"><img src="image1.png"></a> The number w ...

comparing multiple values separated by commas with JavaScript

I need validation using a comma-separated value format. Within the illustration, there are two fields: "Saloon Price" (value: 10,10,10,10) and "Saloon Offer Price" (value: 11,11,11,11). The first value must be less than the second. Saloon price Value & ...

center items alignment with hidden tags

I'm currently facing an issue with the CSS property display: flex, align-items: center Here is a snippet of my HTML and CSS files: * { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Kumbh Sans', sans-serif; } .na ...

Moving the sidebar from the app component to a separate component in Angular results in a situation where the sidebar does not maintain full height when the page is scrolled down

Within my Angular application, I have implemented a sidebar as a separate component. Previously, the content of the sidebar was housed within the main app component's HTML page, and it functioned properly by taking up the full height of the page when ...

Unable to eliminate the beforeunload event

The code below is used to display a default pop-up when the page is refreshed or closed: var myEvent = window.attachEvent || window.addEventListener; var chkevent = window.attachEvent ? 'onbeforeunload' : 'beforeunload'; /// make IE7, ...

Extracting content from HTML-formatted email

When I receive inbound emails with HTML formatting that has been copied and pasted from office applications like Outlook, it often causes formatting issues when displayed on my HTML enabled UI. To address this problem, I usually copy the HTML content to an ...

What is the best way to establish personalized CSS styles specific to each subdomain?

I am in the process of establishing a multi-tenant application with a single instance and single database setup. The backend infrastructure is built using Ruby on Rails, while the frontend is handled by a separate AngularJS app integrated with a Rails fram ...

Display a message indicating unavailability when no events are scheduled and adjust the background color in FullCalendar

In one of my projects, I am utilizing jQuery FullCalendar to schedule appointments for doctors. The doctors should be able to specify their availability between 9 AM - 5 PM on weekdays. If this is not set, the background color of the spans of time not boo ...

Inconsistencies in the Buffer Type within Node.js

Can someone help me understand how Buffer Type works in NodeJs? I'm new to it and struggling with a specific situation. Here's an example: In my "User" Schema, I have a field called "picture". var UserSchema = new mongoose.Schema({ name: Stri ...

What is the best way to test the output of HTML code in a unit test scenario

I am new to web development and testing, taking it slow. I have a website with a button that reveals information when clicked. How can I create a test case to ensure that the displayed output is correct? I need to verify that the text appears on the scre ...

I created a customized version of jQuery tabs, but I am looking for an external link to display the tab content and to style the original navigation

I've been experimenting with modifying a tabs script in jQuery that I came across. It seems like my attempt to enhance it has made things more complex than necessary. While I know creating tabs with jQuery is simple, I wanted to create my own version ...

What is the best way to implement a function on every item within a specific class?

I'm new to coding and I have a website that showcases job listings. I want to create a function that dynamically changes the logo of a company based on the first 50 characters of the company name mentioned. The current function only works for the firs ...

What is the best method to retrieve a global variable from two separate PHP files?

Within file1.php, there is a variable: global $name; $name = ""; In the same directory, within file2.php, there is: <label> <span>Username:</span> <input id="name" type="text" name="username" value ="<?php echo $GLOBALS[& ...