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

如何仅用display:flex创建120px高度的div?(禁用float,仅用div)

Solution: Create a 120px Height Div with Flexbox

Hey there! Let’s tweak your existing code to build that 120px height div using only flexbox (no floats, just div tags) — I’ll break down two common scenarios based on what you’re aiming for:

Option 1: Set the outer flex container to 120px height

If you want the main .flex-container div to be exactly 120px tall, simply add a height: 120px property to its CSS. Flexbox will handle arranging child elements within this fixed height, and you can optionally adjust alignment to polish the look:

.flex-container {
  display: flex;
  flex-wrap: wrap;
  background-color: DodgerBlue;
  width: 240px;
  height: 120px; /* Add this line to set container height */
  align-items: center; /* Optional: Vertically centers child content */
}

.flex-container>div {
  background-color: #f1f1f1;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px; /* Adjusted to match child height for proper text alignment */
  font-size: 30px;
}
<div class="flex-container">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>

Option 2: Make individual child divs 120px tall

If your goal is to have each inner div be 120px high, update the height value in the child div’s CSS rule. The flex container will automatically expand to fit these taller elements (or you can set a fixed height on the container if you want to constrain it):

.flex-container {
  display: flex;
  flex-wrap: wrap;
  background-color: DodgerBlue;
  width: 240px;
}

.flex-container>div {
  background-color: #f1f1f1;
  width: 60px;
  height: 120px; /* Change this value to 120px */
  text-align: center;
  line-height: 120px; /* Match height to vertically center text */
  font-size: 30px;
}

Quick Tips:

  • We’re strictly using flexbox (display: flex) with no float properties, and only div tags as requested.
  • Matching line-height to the div’s height ensures your text stays perfectly vertically centered, which fixes the misalignment from your original 75px line-height on a 60px tall child div.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:26:04