首页 > 解决方案 > 锚标签内的 div 不占用整个宽度?HTML 和 CSS

问题描述

好的,所以我在div标签内有一个a标签。具有“项目”类的a标签具有背景图像。我正在尝试制作几个小300px by 300px 盒子,其中有一个图像,文本居中(垂直和水平),以便您单击图像,它会带您到一个链接。

我想获得悬停效果(在桌面上),这样当您越过这个a图像为 a 的标签时,background image图像会变暗,从而使白色文本更加明显。在移动设备上,此图像始终变暗,因此文本清晰可见。

问题是:我的一切工作正常,但标签div内的“覆盖”a并没有占据 a 标签的整个宽度(300 像素 x 300 像素框)。因此,当我将鼠标悬停在a标签上时,“叠加层”div变暗时,两边都有一点不暗的空间。

这是一些代码:

项目部分的 HTML:

<!-- Projects Showcase Section -->
<div class="projects-section">

    <div class="wrapper">

        <a href="link-to-project" class="project">
            <div class="overlay">
                <h1>Project Name</h1>
            </div>
        </a>

        <a href="link-to-project" class="project">
            <div class="overlay">
                <h1>Project Name</h1>
            </div>
        </a>

        <a href="link-to-project" class="project">
            <div class="overlay">
                <h1>Project Name</h1>
            </div>
        </a>

    </div>
</div> 

CSS:

.projects-section {
    width: 90%;
    margin: 0 auto;
    text-align: center;
}

.wrapper {
    margin-bottom: 50px;
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    text-align: center;
}

.project {
    width: 300px;
    height: 300px;
    background-image: url('../assets/img/p1-min.jpg');
    background-repeat: no-repeat;
    background-size: cover;
    border-radius: 20px;
    margin: 20px 20px 0 20px;
}

.project:nth-child(2) {
    width: 300px;
    height: 300px;
    background-image: url('../assets/img/p2-min.jpg');
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    border-radius: 20px;
}

.project:nth-child(3) {
    width: 300px;
    height: 300px;
    background-image: url('../assets/img/p3-min.jpg');
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center;
    border-radius: 20px;
}

a {
    text-decoration: none;
    font-weight: bold;
    font-family: 'Roboto', sans-serif;
    color: white;
    font-size: 30px;
    padding: 0 10px;
}

.project .overlay {
    height: 100%;
    width: 100%;
    margin: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: 0.4s all ease;
    border-radius: 20px;
}

.overlay:hover {
    background-color: rgba(0, 0, 0, 0.5);
}

这是问题的样子: 问题

如您所见,“叠加层”的左侧和右侧div没有完全展开以适合a标签内部,因此很明显那里有一个 div。

请帮我修一下,谢谢。

标签: javascriptjqueryhtmlcss

解决方案


如果您删除锚点上的左/右填充,并将.project元素的宽度扩展到 320 像素,它应该看起来像您想要的那样 - 尽管我不确定您是否将填充用于其他目的。

.project {
    width: 320px;
    height: 300px;
    background-image: url('http://via.placeholder.com/300x300');
    background-repeat: no-repeat;
    background-size: cover;
    border-radius: 20px;
    margin: 20px 20px 0 20px;
}

a {
    text-decoration: none;
    font-weight: bold;
    font-family: 'Roboto', sans-serif;
    color: white;
    font-size: 30px;
    padding: 0;
}

http://jsfiddle.net/dtwLjqx4/


推荐阅读