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

Flexbox布局中如何让a标签撑满父容器显示完整绿色背景

问题描述

我只会一点英语,目前在尝试使用Flexbox进行布局。

我的HTML代码如下:

<div class="title">
    <div class="left-title">
        <a href="#">Lorem Ipsum</a>
    </div>
    <div class="right-title">June 18, 2021</div>
</div>

我的CSS代码如下:

.title {
    display: flex;
    justify-content: space-between;
    width: 100%;
    background-color: red;
}

.left-title {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

.left-title a {
    line-height: 48px;
    background-color: green;
    font-weight: bold;
    padding: 0 1em;
    text-decoration: none;
    height: 48px;
    color: black;
}

.left-title a:hover {
    color: white;
}

.right-title {
    white-space: nowrap;
    line-height: 48px;
    padding: 0 1em;
    background-color: black;
    color: white;
    font-weight: bold;
}

我需要让a标签撑满整个父容器,显示完整的绿色背景,请问该如何实现该需求?


解决方案

修改两处CSS规则即可实现需求:

  1. 给.left-title添加flex: 1属性,让其占满.title容器除右侧日期区域外的所有剩余空间
  2. 给.left-title a添加display: block属性,让a标签从默认行内元素变为块级元素,自动撑满父容器宽度

修改后的完整CSS代码如下:

.title {
    display: flex;
    justify-content: space-between;
    width: 100%;
    background-color: red;
}

.left-title {
    flex: 1;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

.left-title a {
    display: block;
    line-height: 48px;
    background-color: green;
    font-weight: bold;
    padding: 0 1em;
    text-decoration: none;
    height: 48px;
    color: black;
}

.left-title a:hover {
    color: white;
}

.right-title {
    white-space: nowrap;
    line-height: 48px;
    padding: 0 1em;
    background-color: black;
    color: white;
    font-weight: bold;
}

原代码中.left-title宽度默认由内部内容撑开,所以绿色背景仅覆盖文本区域,添加flex:1后会自动填充flex容器的剩余可用空间,a标签设为块级元素后会自动占满父容器的全部宽度,即可实现完整绿色背景效果。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 18:09:02