Home >Web Front-end >CSS Tutorial >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!