How to center a div both vertically and horizontally when height is not specified?

Is it possible to center a div on a webpage without specifying a fixed height, so that the height adjusts dynamically based on the content? I am willing to consider JS/jQuery solutions with fallback options but would prefer a pure CSS approach.

Currently, my code centers the div but requires a set height:

HTML

<div class="card">Lorem ipsum dolor sit amet, minim molestie argumentum est at, 
pri legere torquatos instructior ex. Vis id odio atomorum oportere, quem modo fabellas sit 
at, dicat semper est ne. Apeirian detraxit pri eu. No solum accusam has. Ius ne harum mundi 
clita, eu pro tation audiam.
</div>

CSS

.card {
    background-color: #1d1d1d; /* IE fallback */
    background-color: rgba(29, 29, 29, 0.95);
    color: #fff;
    display: inline-block;
    margin: auto;
    position: absolute;
    bottom: 0;
    top: 0;
    left: 0;
    right: 0;   
    padding: 30px 35px;
    outline: 2px solid #3B3A37;
    outline-offset: -9px;
    width: 320px;
    height: 350px;
}

Fiddle Link

This question stands out from previous discussions due to its timing and the advancements in CSS3 since the earlier topic was raised in 2011. New functionalities in CSS3 may provide an improved solution for this requirement.

Answer №1

To achieve this effect, simply apply top:50%; and transform: translateY(-50%); to the .card element.

Check out the demo on JSFiddle - DEMO or view it in full screen here

CSS:

html, body {
    height:100%;
    margin: 0px;
}
.card {
    background-color: #1d1d1d;
    /* IE fallback */
    background-color: rgba(29, 29, 29, 0.95);
    color: #fff;
    padding: 30px 35px;
    outline: 2px solid #3B3A37;
    outline-offset: -9px;
    width: 320px;
    position: relative;
    margin: 0 auto;
    top:50%;
    -webkit-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    -moz-transform: translateY(-50%);
    -o-transform: translateY(-50%);
    transform: translateY(-50%);
}

For further reading:

Answer №2

If you're looking for a CSS solution that doesn't require specifying height:

  • You can implement CSS3 flexbox like this:

    body {
      display:flex;
      align-items:center;
    }
    

    View Updated Fiddle

  • Alternatively, you can utilize the translate technique:

    .card {
      position: absolute;
      top: 50%;
      left:50%;
      transform: translateX(-50%) translateY(-50%);
      /* other styles */
    }
    

    View Updated Fiddle

Browser support:

Note: For older browser compatibility, consider using JavaScript fallbacks.

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

Is it possible to extract external JSON data using JQuery's $.getJSON function?

I am trying to retrieve a quote from the iheartquotes website and display it within a div when my webpage loads. However, for some reason, the code I have written is not working as expected. <script type="text/javascript"> $(document).ready( ...

Updating Dropdown Selection in Angular 9 and 10

Is there a way to set attributes to "Selected" in HTML options based on a condition from a *ngFor loop in response.body of the component ts file? Below is the dropdown code: <select [(ngModel)]="customer.id"> <option *ngFor="let location of lo ...

Can someone explain the reason behind the sizing discrepancies of HTML and body elements when emulating a mobile device in Chrome Developer Tools?

Recently, I attempted to load a tool on my phone that I have been developing for internal use at my workplace. Upon loading the tool, I noticed some discrepancies in the display, which I had anticipated. However, one specific element seemed particularly u ...

Perform PHP function without refreshing the page when clicking

I have a PHP script that displays an alert box with the options OK or CANCEL. If OK is clicked, it redirects to a link that triggers a PHP function to delete the selected image. <?php //echo $pictures['binId']; if(count($other_images)) { ...

Connecting to a specific section of a webpage

I'm facing an issue with my menu links on a webpage where they are not directing to the intended header sections but instead jumping to the end of the sections, creating confusion for users. I have attempted a couple of solutions; here is the first at ...

Is there a way to remove the entire row if I dismiss a bootstrap alert?

Hey there! I'm having a little issue with an alert in a row-fluid. Curious to see? Check out my fiddle. So, when I click the "x" button to dismiss the alert, the row is still visible. Any idea how I can make the entire row disappear when I dismiss it? ...

"Interactive Connect 4 Game in Javascript - Drop the disk into the bottom row of the chosen

Check out this awesome Connect4 game I found: http://codepen.io/anon/pen/lmFJf I have a specific goal in mind for the game. When I click on an empty space in any column, I want it to automatically drop into the lowest available spot in that column, follow ...

Retrieve information from a JSON file containing multiple JSON objects for viewing purposes

Looking for a solution to access and display specific elements from a JSON object containing multiple JSON objects. The elements needed are: 1) CampaignName 2) Start date 3) End date An attempt has been made with code that resulted in an error displayed ...

Expansive full screen image proportions

Is there a way to showcase an image on the entire screen without distorting it, while maintaining its aspect ratio in either HTML or Javascript? The desired outcome is for the image to be centered and: - Have a height of 100% and a width of x% (where "x" ...

Ways to modify the cursor of a disabled ImageButton on an ASP.Net webpage

Within a ListView, I have dynamically generated ImageButtons. If an image does not have a link, I want to make it disabled. In the ItemDataBound event, I attempted the following approach: img.Enabled = False img.DescriptionUrl = "javascript:void(0);" img. ...

Having difficulty inserting an image with style="background-image:url(' ')" in Rails from the database

Hi everyone! I am new to both Rails and Stack Overflow, and I would really appreciate it if someone could guide me here. I am currently working on a test site that resembles a personal blog. It's mainly for showcasing one user's portfolio. In t ...

Choosing multiple lists in Angular 2 can be achieved through a simple process

I am looking to create a functionality where, upon clicking on multiple lists, the color changes from grey to pink. Clicking again will revert the color back to grey. How can I achieve this using class binding? Below is the code snippet I have tried with ...

PHP - display the modified page with the updates applied

I currently have an HTML page where users can input information and submit a form to change database information. Typically, the submit button calls a PHP file on the server to process the data. However, I am looking for a way for this PHP file to return t ...

Encountering issues with the Bootstrap image gallery display

I'm a newcomer to Bootstrap and I want to create an image gallery. This is what I expect: https://i.sstatic.net/DKxMC.jpg However, what I'm getting looks like this: https://i.sstatic.net/KkrAG.jpg This is the HTML code I have so far: <div ...

Difficulty with Flexbox in Internet Explorer 11 when utilizing a Bootstrap .badge element

At the moment, I am dealing with a flex-row that contains an element that grows with the available space and a badge that should be aligned to the end without growing. However, when using flex-grow: 0 in IE11, the span.badge does not even take up the width ...

Tips for aligning text vertically in a column using CSS columns

Can text be vertically aligned in CSS columns? For example, aligning text to the top, center, or bottom within each column? I attempted to use vertical-align, but it doesn't seem to work on an unordered list or its items: html <div class="nav-ba ...

Issue with docker-composer module not being detected specifically on windows operating system

We are currently in the process of setting up a container running node.js with docker (specifically docker-compose, as we plan to incorporate mongodb later). Our approach involves copying the package.json in the Dockerfile and then creating a volume mount ...

AngularJS - Determine the correct condition or make a choice from the available options

I'm having trouble figuring out how to save the option I select to a viewmodel. The ng-model should save whatever option I choose, and if nothing is selected, the value should default to "Select One." The available options are YES (true) / NO (false). ...

The functionality of Google Maps code is limited on Android devices because the map feature is not available

After updating the Google Maps embed code to be responsive for mobile devices, I discovered that the map still won't display on Android or iPhone. The following is the modified code. Can anyone assist me in resolving this issue so that the map can sho ...

displaying a loading component in a Vue application only when necessary

Below is the vue code snippet I'm working with: <div v-if="team_members && team_members.length > 0"> screen1 </div> <div v-else> <svg viewBox="0 0 50 50" class="spinner"> ...