Home >Web Front-end >CSS Tutorial >How Can I Horizontally Align Two Divs Without Changing the HTML?

How Can I Horizontally Align Two Divs Without Changing the HTML?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-17 08:49:04200browse

How Can I Horizontally Align Two Divs Without Changing the HTML?

Aligning Elements Horizontally without Altering Markup

Suppose you have two divs, #element1 and #element2, positioned horizontally using CSS. However, due to content variations in #element2, it doesn't align perfectly alongside #element1. You need a way to align them regardless of content or browser differences without modifying the HTML structure.

Solution: Using Inline-block Display

To accomplish this alignment, you can employ the display: inline-block property for both elements:

#element1 {
  display: inline-block;
  margin-right: 10px; /* Set padding between the elements */
}

#element2 {
  display: inline-block;
}

By setting display: inline-block, the elements will behave similarly to inline elements but maintain their block-level properties. This allows you to position them horizontally while preserving their original width and height. The margin-right property on #element1 introduces the desired spacing between the elements.

Example

Here's an example that demonstrates the alignment:

<style type="text/css">
  #element1 {
    display: inline-block;
    margin-right: 10px;
  }

  #element2 {
    display: inline-block;
  }
</style>
<div>

This solution effectively aligns #element2 next to #element1, maintaining a consistent padding regardless of #element2's variable width.

The above is the detailed content of How Can I Horizontally Align Two Divs Without Changing the HTML?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn