如何水平居中div?实现子div居中且段落左对齐的方案
Hey there! Let's get this sorted out for you. You want your child div to sit perfectly centered horizontally within its parent, while keeping the paragraph text inside left-aligned—this is a super common layout need, and there are a couple of solid ways to pull it off.
Option 1: Use Flexbox (Modern, Flexible Approach)
Flexbox is my go-to for this kind of centering because it's clean and works great for more complex layouts down the line. We'll add flex properties to the parent div to center its child, and since paragraphs are left-aligned by default, your text will stay exactly where you want it.
Here's the adjusted code:
<div style="width:100%; display: flex; justify-content: center;"> <div style="width:50%; background:#000;"> <p style="color:#fff;">Text must be left.</p> </div> </div>
How it works:
display: flexturns the parent into a flex containerjustify-content: centertells the flex container to horizontally center all its direct children (your 50% width div)- The paragraph keeps its default
text-align: leftbehavior, so no extra styling needed here.
Option 2: Traditional Margin Auto Method
If you prefer a more old-school approach that works in all browsers (including older ones that don't fully support flex), you can use margin: 0 auto on the child div. This tells the browser to automatically split the available horizontal space equally on both sides of the child, centering it.
Adjusted code:
<div style="width:100%;"> <div style="width:50%; background:#000; margin: 0 auto;"> <p style="color:#fff;">Text must be left.</p> </div> </div>
Quick Note:
If you ever run into a case where the paragraph isn't left-aligned (maybe due to global styles overriding defaults), just add text-align: left to the <p> element's style to explicitly lock in that behavior.
内容的提问来源于stack exchange,提问作者Rushabh Shah

