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

如何让Div占满可用宽高、实现Div等高对齐及文本左上定位

Fixing Equal Height Divs and Top-Left Text Positioning

Hey there! Let's tackle those two issues you're facing—getting the two divs to match heights and keeping the "Data" text fixed in the top-left corner. Here are a couple of clean, modern solutions that'll do the trick:

Flexbox is the simplest and most widely supported approach for this scenario. It automatically makes child elements equal in height, and controlling text alignment is a breeze:

<div style="display: flex;">
  <!-- First div: takes remaining space, keeps "Data" top-left -->
  <div style="background-color: #ccc; flex: 1; display: flex; align-items: flex-start;">
    Data
  </div>
  <!-- Second div: fixed width -->
  <div style="background-color: #ccc; width: 80px;">
    <span>Work: 22</span>
    <span>Todos: 33</span>
  </div>
</div>

Key Details:

  • display: flex on the parent container: Activates Flexbox, which defaults to stretching child elements to the same height (thanks to align-items: stretch).
  • flex: 1 on the first child div: Makes it take up all remaining space in the parent, so it fills the width next to the fixed-size second div.
  • display: flex; align-items: flex-start on the first div: Ensures "Data" stays pinned to the top-left, even if you add more content to this div later.

Method 2: CSS Grid

If you prefer Grid layout, it's equally effective for equal heights and controlled sizing:

<div style="display: grid; grid-template-columns: 1fr 80px;">
  <div style="background-color: #ccc; display: flex; align-items: flex-start;">
    Data
  </div>
  <div style="background-color: #ccc;">
    <span>Work: 22</span>
    <span>Todos: 33</span>
  </div>
</div>

Key Details:

  • grid-template-columns: 1fr 80px: Defines the column widths—1fr means "take all remaining space," while the second column stays fixed at 80px.
  • Grid layout automatically makes child elements the same height, no extra settings needed.

Optional: Clean Up the Second Div's Content

If you want the text in the second div to look neater, add a few styles to arrange it vertically:

<div style="display: flex;">
  <div style="background-color: #ccc; flex: 1; display: flex; align-items: flex-start;">
    Data
  </div>
  <div style="background-color: #ccc; width: 80px; display: flex; flex-direction: column; gap: 4px;">
    <span>Work: 22</span>
    <span>Todos: 33</span>
  </div>
</div>

The flex-direction: column stacks the text lines vertically, and gap: 4px adds a small space between them for better readability.

内容的提问来源于stack exchange,提问作者StrugglingCoder

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:12:55