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

Angular项目中:first-child选择器无法设置Input宽高问题

解决Angular项目中Flex布局下Input宽高不生效及宽度不一致问题

问题1:Input的:first-child样式不生效

你的HTML结构里,.Player容器的第一个子元素是<p>标签,并非input。:first-child选择器仅匹配父元素的第一个直接子元素,所以.lineTwo:first-child无法命中input;而button能生效是因为它确实是.Player的最后一个直接子元素,last-child能正确匹配。

修复方案

把input和button放到单独的容器中,让它们成为同级兄弟元素,这样:first-child和:last-child就能正常匹配:

修改后的HTML代码:

<div class="Player">
    <p id="Player"> Test </p>
    <div class="lineTwo-container">
        <input class="lineTwo">
        <button class="lineTwo">Test</button>
    </div>
</div>

对应的SCSS调整:

.Player {
    position: relative;
    width: 80%;
    margin: auto;
    p {
        border: 1px solid rgba($color: #000000, $alpha: 0.3);
        font-size: 20px;
        padding: 16px;
        height: 500px;
    }

    .lineTwo-container {
        position: absolute;
        width: 100%;
        display: flex;
    }

    .lineTwo {
        font-size: 15px;
        &:first-child {
            flex: 0 0 50%;
            left: 0;
        }
        &:last-child {
            flex: 0 0 50%;
            right: 0;
            display: flex;
            justify-content: center;
        }
    }
}

问题2:Input和Button宽度不一致

这是因为input默认的box-sizing为content-box,而button默认box-sizing通常是border-box(浏览器默认样式差异)。使用content-box时,设置的width不包含padding和border,导致实际宽度超出预期。

修复方案

统一设置.lineTwo的盒模型为border-box,让width包含padding和border:

.lineTwo {
    box-sizing: border-box;
    // 其余样式...
}

或者在全局样式中统一所有元素的盒模型:

* {
    box-sizing: border-box;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 19:36:20