You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何水平居中div?实现子div居中且段落左对齐的方案

Solution for Centering Child Div Horizontally with Left-Aligned Paragraph

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: flex turns the parent into a flex container
  • justify-content: center tells the flex container to horizontally center all its direct children (your 50% width div)
  • The paragraph keeps its default text-align: left behavior, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:10:06