Home >Web Front-end >CSS Tutorial >Aligning elements in CSS
CSS Alignment Demystified: A Comprehensive Guide (Part 1)
Aligning elements in CSS can be surprisingly challenging. Let's tackle this head-on and learn how to effectively position elements.
We'll begin with some sample HTML:
<code class="language-html"><div class="outer-div"> <div class="inner-div"></div> <p>Initial rendering without CSS:</p> <img alt="Initial rendering" src="/uploads/20250128/173802269967981f2bdc9c3.jpg" loading="lazy"> <p>Adding CSS for improved styling:</p> <img alt="Improved styling" src="/uploads/20250128/173802270067981f2c02601.jpg" loading="lazy"> <p>This is a basic example.</p> </div></code>
And the corresponding CSS:
<code class="language-css">.outer-div { /* Alignment styles will be added here */ } .inner-div { width: 150px; height: 150px; background-color: blue; /* More alignment styles here */ } h1, p { font-family: sans-serif; }</code>
Let's center our elements. Adding display: flex;
and justify-content: center;
to .outer-div
yields:
<code class="language-css">.outer-div { display: flex; justify-content: center; }</code>
Applying the same to .inner-div
initially produces unexpected results. Removing the width
and height
properties from .inner-div
improves the outcome, but it's not ideal.
Let's adjust the HTML slightly. The following updated HTML and CSS provides a better illustration:
<code class="language-html"><div class="outer-div"> <div class="inner-div">Centered Content</div> </div></code>
Changing justify-content: center;
to justify-content: space-between;
in .outer-div
demonstrates another useful alignment technique.
This covers the fundamentals. Stay tuned for Part 2! Share your CSS alignment tips and tricks below!
The above is the detailed content of Aligning elements in CSS. For more information, please follow other related articles on the PHP Chinese website!