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

如何实现文本与水平线宽度对齐?HTML/CSS代码问题求助

解决文本与水平线宽度一致的问题

问题分析

你的代码存在几个关键问题导致水平线宽度和文本不匹配:

  • HTML语法错误:<div class="title horizontal-line"></span> 标签闭合错误,应改为</div>
  • CSS选择器错误:.company-name 需改为#company-name(HTML中使用的是id属性而非class)
  • 块级元素默认占满父容器宽度,导致水平线宽度超出文本范围

修正后的代码

HTML代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="styles.css">
    <title>project-1</title>
</head>
<body>
    <header>
        <div id="company-name">
                <p class="title">OneClick</p>
                <div class="title horizontal-line"></div>
                <p id="p-clear" class="title">Tech Solution</p>
        </div>
    </header>

    <footer></footer>
</body>
</html>

CSS代码

.title{
    margin:0;
    padding:0;
    /* 让标题收缩至自身内容宽度 */
    width: fit-content;
}
.horizontal-line{
    border-top: 2px solid black;
    /* 让水平线匹配标题宽度 */
    width: fit-content;
}
#company-name{
    width:20%;
    /* 可选:若需要标题和水平线居中,取消下面注释 */
    /* text-align: center; */
}

额外优化方案

如果希望整个公司名称容器的宽度由文本自动决定,可将#company-name的width:20%替换为width: fit-content;,这样容器只会占用文本所需的宽度,水平线会自然和文本对齐。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 22:12:39