Achieving the perfect balance: Centering and fitting an image into a div without any loss

As I delve into learning CSS, I keep stumbling upon solutions that are almost there for what should be a simple task. Being at a very basic stage of my learning journey, I am struggling with figuring things out.

My current challenge involves placing one image on a page in a horizontal and vertical center alignment. The image should be contained within a div that occupies 80% of the window height and width. Additionally, I want the image to automatically stretch to fill either the height or width of the div, depending on which dimension is smaller.

While this may seem straightforward to many, it is quite puzzling for me as a beginner. Any guidance on how to achieve this would be greatly appreciated.

To better illustrate my point, I have created an example:

Answer №1

For a solution to your query, view this example

This method accomplishes most of your requirements. To adjust the image height to 80% of the available space when the screen height is less than the intrinsic image height, you may need to incorporate additional JavaScript.

<body>
<div id="container">
        <img src="http://dummyimage.com/600x400/000/fff.jpg" alt="appropriate alt text">
</div>
</body>

html,
body{
    height:100%;
    width:100%;
    margin:0;
    padding:0;
    background-color: #eee;
}
#container{
    margin: auto;
    width:100%;
    height:100%;
    text-align:center;
    font-size:0;
    white-space:nowrap;
    background:#aae;
}
#container:before{
    content:'';
    display:inline-block;
    height:100%;
    vertical-align:middle;
}
img {
    width:80%;
    height:auto;
    display:inline-block;
    vertical-align:middle;
    background:#fff;
}

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

Sharing a document that contains a linked image file using a relative path through the `publish` feature

I have reviewed the documentation and tested the steps provided in this example, but I am still unable to find a solution for the issue at hand. Based on the documentation, the image file should either be located in the same path as the MATLAB script bein ...

Executing cssnano Using the Command Prompt

Although I'm not an expert in node JS, I have come across cssnano as a JavaScript tool for minifying CSS, which apparently does a more sophisticated job compared to the outdated YUI compressor. My only issue is that I am struggling to understand how t ...

Customizing colors in React Material UI

Can colors in Material UI be overridden without the use of JS? Is it possible to override colors using CSS alone? ...

Trouble getting custom CSS media queries to function properly alongside Bootstrap 3

I've encountered an issue while using bootstrap 3 with jquery UI to implement search and select fields for the user. The CSS code seems to be working fine on larger screens, but it's completely non-functional on smaller screens. I tried applying ...

Struggling to incorporate a three-strike mechanism into my JavaScript game

I need to implement a feature where the user can make up to 2 mistakes before losing the game. Here's what I need to do: - Set up a global variable to keep track of the number of mistakes - Initialize this variable during the startGame function - M ...

How can we use the nth-of-type selector to target a set of eight elements in a

I am trying to style a group of divs in such a way that every set of eight elements will have the same left positioning. Rather than just styling every eighth element individually, I want to apply the styling to groups of eight elements at once. However, ...

angularjs: container holding directive is currently not visible, with a height and width of 0 pixels

When implementing a directive in this way, the actual element (<a-directive>) appears to have dimensions of 0px height and 0px width. View jsfiddle example var myApp = angular.module('myApp', []).directive('aDirective', function ...

The challenge of styling React components

Starting a new project with React and Redux has presented me with the challenge of deciding on a styling method. As a newcomer to React, I want to choose a method that won't compromise performance, will offer all CSS3 features, and is easy to maintain ...

Is it possible to run a Universal Windows Platform desktop app on an Android mobile device?

After successfully developing a Universal Windows Platform app in Visual Studio using WinJS, JavaScript, CSS and HTML, I am now interested in leveraging the same code base to create an Android application. Could you guide me on the necessary steps to run ...

Leveraging the power of CSS id selectors to customize the appearance of a Grid

In my current CSS file, I have defined two id selectors: #TableHead { font-family: Arial, Helvetica, sans-serif; font-size:11px; font-weight: bold; color: #000000; border-top-width: thin; border-top-style: solid; border-top-color: #A9AAAA; border-bottom-w ...

Using @at-root seems to be causing an error when combining the "a" selector with

I encountered an issue when attempting to use @at-root and Interpolation in my Sass code. Despite using a standard example for testing, I still receive an error: .button { @at-root a#{&} { color: green; } } Error sass/Site.scss (Line 28 of s ...

Conceal a div containing a specific class during the page's loading process, then reveal it once the

Is there a way to hide a specific div class while a page is loading? Here is the structure I am working with: <div id ="container"> <div class="project-item tv"></div> <div class="project-item radio"></div> <div class="pro ...

retrieve data with the help of DOMDocument

I'm currently working on extracting a specific value from the HTML snippet below using DOMDocument: <h3> <meta itemprop="priceCurrency" content="EUR">€ <meta itemprop="price" content="465.0000">465 </h3> The value ...

Preventing Background Scrolling While Modal is Open in React - Using 'position: fixed' causes the page to unexpectedly scroll back to the top

Currently working on a React website where users can scroll through various posts on the homepage. Each post includes a '...' menu that, when clicked, opens up a modal with additional options. In order to prevent the background from scrolling w ...

By default, Nuxt 2.15.7 is automatically installed when you create a new Nuxt app

I am looking to develop a Nuxt app (version 3) using Vue. However, when I run the command npm create nuxt-app@version mousa, it automatically installs Nuxt2. How can I install Nuxt3 instead with this command? ...

Creating a webpage header with Javascript to mimic an existing design

I am in the process of building a website with 5 different pages, but I want the header to remain consistent across all pages. To achieve this, I plan to use an external JavaScript file (.js). The header includes the website name (displayed as an image) an ...

Gallery of Disappearing Images

I am encountering issues with the image gallery on my website, as it seems to create a space to the right when viewed on screens smaller than 350px. This results in a gap on the entire right side of the page. My goal is to make this image gallery responsiv ...

A guide to using jQuery to execute mathematical operations from a string

Currently, I am working on developing a calculator using jQuery. My main concern is how to carry out mathematical operations from a string and showcase the calculator actions in the output box. $(document).ready(function() { $("input[type='button ...

Steps for accessing registration form data once the signup button has been clicked

Hello everyone! I have a code that includes login and registration forms as tabs. When we click on either one, it goes to the respective form. Now, I want to make a change by removing the Register tab and adding it as a signup button next to the login butt ...

Changing datetime-local format from European to American dates

<input type="datetime-local"> While this input retrieves the local time from your PC, I'm curious if there's a way to make it display as US time specifically. ...