Vertically Centering Content Within a Div (Even with Variable Height)

2024-07-27

Normally, elements like text or images inside a div flow from top to bottom. Just setting the div's height won't center the content because the content itself might have a different height.

The Solution: Using a Pseudo-Element

The trick is to create a hidden helper element inside the div using a pseudo-element like :after. This pseudo-element acts like a child element but is inserted with CSS.

The CSS Code:

Here's the CSS breakdown:

  • .container:after: This targets the pseudo-element created after the content within the div. We set:

    • content: '';: This makes the pseudo-element invisible.
    • display: inline-block;: This allows the pseudo-element to take up space alongside the content.
    • height: 100%;: This makes the pseudo-element the same height as the container div.
    • vertical-align: middle;: This is the key! This aligns the vertical center of the pseudo-element with the vertical center of the content.
    • width: 0;: This sets the width of the pseudo-element to zero, making it invisible horizontally.
  • .child: This styles the actual content you want to center. We set:

    • display: inline-block;: This makes the content behave similarly to the pseudo-element.
    • vertical-align: middle;: This aligns the vertical center of the content with the vertical center of the pseudo-element (which is already centered due to its height).
    • white-space: normal;: This allows line breaks within the content if needed.

How it Works:

By creating a hidden element with vertical-align: middle; that takes up the full height of the container, we essentially create a reference point for vertical centering. The actual content is then aligned to the middle of this reference point, achieving vertical centering regardless of its own height.

Additional Notes:

This method doesn't center horizontally by default. You can add text-align: center; to the .container class for horizontal centering.




<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Vertically Centered Content</title>
  <style>
    .container {
      width: 200px;
      height: 150px; /* Adjust height as needed */
      background-color: #eee;
      white-space: nowrap; /* Prevent line breaks */
      text-align: center; /* Optional: Center horizontally */
    }

    .container:after {
      content: '';
      display: inline-block;
      height: 100%;
      vertical-align: middle;
      width: 0;
    }

    .child {
      display: inline-block;
      vertical-align: middle;
      white-space: normal; /* Allow line breaks */
    }
  </style>
</head>
<body>
  <div class="container">
    <span class="child">This content can have variable height. It will be vertically centered.</span>
  </div>
</body>
</html>

This code creates a container div with a light grey background (#eee). Inside the container, we have a span element with the class child that holds the actual content.

The CSS styles:

  • Set the width and height of the container (width: 200px; height: 150px;). You can adjust these values as needed.
  • Use white-space: nowrap; to prevent line breaks within the container.
  • Target the pseudo-element created after the content using .container:after. This element has:
    • No content (content: '') - making it invisible.
    • display: inline-block; to behave similarly to the content.
    • height: 100%; to match the height of the container.
    • vertical-align: middle; for vertical centering.
    • width: 0; to hide it horizontally.
  • Style the content with the class child:
    • display: inline-block; for proper alignment.
    • vertical-align: middle; to vertically align with the pseudo-element (already centered).



Flexbox offers a powerful and modern way to achieve vertical centering. Here's how:

<div class="container">
  <span class="child">This content can have variable height. It will be vertically centered.</span>
</div>
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 200px; /* Adjust width as needed */
  height: 150px; /* Adjust height as needed */
  background-color: #eee;
}

.child {
  /* No additional styles needed for the content */
}

Explanation:

  • We set the container's display property to flex. This activates flexbox layout.
  • justify-content: center; centers the content horizontally within the container.
  • align-items: center; vertically centers the content along the cross-axis (which is the vertical axis in this case).
  • We don't need any specific styles for the child element (.child) as the flexbox container handles the centering.

Absolute Positioning and Margin:

This method uses absolute positioning and margins for centering. Here's the code:

<div class="container">
  <span class="child">This content can have variable height. It will be vertically centered.</span>
</div>
.container {
  position: relative;
  width: 200px; /* Adjust width as needed */
  height: 150px; /* Adjust height as needed */
  background-color: #eee;
}

.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%); /* Offset for centering */
}
  • We set the container's position to relative to establish a reference point for absolute positioning.
  • The child element gets position: absolute; to remove it from the normal document flow.
  • top: 50%; and left: 50%; position the element at the center of the container.
  • transform: translate(-50%, -50%); offsets the element by half its width and height on both axes, effectively centering it within the container regardless of its own size.

css vertical-alignment



Example Codes for Customizing Numbering in HTML Ordered Lists

In HTML, ordered lists are created using the <ol> tag.Each item within the list is defined using the <li> tag.By default...


Understanding HTML, CSS, and XHTML for 100% Min-Height Layouts

HTML (HyperText Markup Language) is the building block of web pages. It defines the structure and content of a webpage using elements like headings...


Tables for Data, DIVs for Design: The Right Tools for the Job in HTML and CSS

Tables (HTML): These are meant for presenting data in a tabular format, like rows and columns. They have elements like <tr> (table row), <td> (table cell), etc...


Optimize Your Webpages: Tools for Unused Resources

Browser Developer Tools: Most modern browsers like Chrome and Firefox have built-in developer tools. These tools allow you to inspect the website's code and identify potential issues...


Conquering Div Alignment: Your Guide to Horizontal Placement in CSS

Two or more divs side-by-side: This is the most common scenario. You want your divs to display horizontally next to each other...



css vertical alignment

Fixing Width Collapse in Percentage-Width Child Elements with Absolutely Positioned Parents in Internet Explorer 7

In IE7, when you set a child element's width as a percentage (%) within an absolutely positioned parent that doesn't have an explicitly defined width


Unveiling Website Fonts: Techniques for Developers and Designers

The most reliable method is using your browser's developer tools. Here's a general process (specific keys might differ slightly):


Interactive Backgrounds with JavaScript: A Guide to Changing Colors on the Fly

Provides the structure and content of a web page.You create elements like <div>, <p>, etc. , to define different sections of your page


Cross-Browser Rounded Corners Made Easy: Mastering the border-radius Property in CSS

In CSS (Cascading Style Sheets), the border-radius property allows you to add a curved effect to the corners of an element's outer border


Enhancing Textarea Usability: The Art of Auto-sizing

We'll create a container element, typically a <div>, to hold the actual <textarea> element and another hidden <div>. This hidden element will be used to mirror the content of the textarea