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

React中使用<a>标签包裹div后元素消失的问题求助

问题原因

你的CSS中.flex-container > div选择器仅作用于flex-container的直接子级div,但被<a>包裹的.sdg1div不再是flex-container的直接子元素,而是<a>的子元素,因此原本给直接子div设置的width、margin等样式无法作用到它。同时<a>标签默认是行内元素,自身没有尺寸,导致内部的.sdg1div也无法正常显示。

解决方案

提供两种可行的修复方法:

方法1:调整CSS选择器,覆盖a标签及其子元素

修改CSS中针对flex子元素的样式,让a标签和直接子div应用相同样式,并确保内部div填充整个a容器:

/* SDG boxes section */
.flex-container {
    display: flex;
    flex-wrap: wrap;
    border-radius: 16px;
    background: linear-gradient(90deg,rgba(244,247,252,0.5) 0%,rgba(244,247,252,0.5) 100%);
    justify-content: center;
}  

/* 让a标签和直接子div共享样式 */
.flex-container > div, .flex-container > a {
    background-color: white;
    width: 18vh;
    margin: 15px;
    text-align: center;
    line-height: 18vh;
    font-size: 30px;
    display: block; /* 将a标签设为块级元素,确保尺寸生效 */
    text-decoration: none; /* 去掉a标签默认下划线 */
}

/* 让a标签内的div铺满容器 */
.flex-container > a > div {
    width: 100%;
    height: 100%;
}

/* 保留原有SDG图标样式 */
/* All SDG icons */
.sdg1 {
    background: url("../assets/SDGIcons/sdg1.png"); 
    background-size: contain;
}

.sdg1:hover {
    -webkit-filter: brightness(60%);
    transition: all 1s ease;
}

.sdg2 {
    background: url("../assets/SDGIcons/sdg2.png"); 
    background-size: contain;
}

.sdg3 {
    background: url("../assets/SDGIcons/sdg3.png"); 
    background-size: contain;
}

.sdg4 {
    background: url("../assets/SDGIcons/sdg4.png"); 
    background-size: contain;
}

.sdg5 {
    background: url("../assets/SDGIcons/sdg5.png"); 
    background-size: contain;
}

.sdg6 {
    background: url("../assets/SDGIcons/sdg6.png"); 
    background-size: contain;
}

.sdg7 {
    background: url("../assets/SDGIcons/sdg7.png"); 
    background-size: contain;
}

方法2:调换结构,将a标签嵌套在div内部

修改React代码,让div保持为flex-container的直接子元素,把a标签放在div内部:

const SdgBackground = () => {
    return (
        <div className="flex-container">
            <div className="sdg1">
                <a href="https://www.un.org/sustainabledevelopment/poverty/"></a>
            </div>
            <div className="sdg2"></div>
            <div className="sdg3"></div>
            <div className="sdg4"></div>
            <div className="sdg5"></div>
            <div className="sdg6"></div>
            <div className="sdg7"></div>
            <div>SDG</div>
            <div>SDG</div>
            <div>SDG</div>
            <div>SDG</div>
            <div>SDG</div>
            <div>SDG</div>
            <div>SDG</div>
            <div>SDG</div>
            <div>SDG</div>
            <div>SDG</div>  
        </div>
    )
}

export default SdgBackground 

同时补充CSS让内部的a标签铺满整个div:

.flex-container > div > a {
    display: block;
    width: 100%;
    height: 100%;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 17:27:26