如何让Div占满可用宽高、实现Div等高对齐及文本左上定位
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:
Method 1: Flexbox (Recommended)
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: flexon the parent container: Activates Flexbox, which defaults to stretching child elements to the same height (thanks toalign-items: stretch).flex: 1on 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-starton 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—1frmeans "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

