【问题标题】:Cannot properly lay out rows using CSS Grid Layout无法使用 CSS 网格布局正确布局行
【发布时间】:2017-03-12 06:19:25
【问题描述】:

我正在尝试将 CSS 网格布局用作 described here

我的问题是,在成功编写了两行网格布局后,我无法正确获取第三行的布局。第三行不知何故盖住了第二行。

下面是代码的基本结构,可以让您了解我正在尝试做什么。我包含所有代码的存储库是here

查看已发布的页面时,很明显前两行布局正确,但不幸的是第三行不符合网格布局(并覆盖在第二行上)。

有人知道我如何正确布置第三行吗?

我的 HTML 结构:

    <body>

    <header class="hero">
    </header>

    <main role="main">

    <section class="tech">
    </section>

    <section class="afford">
        <h1>This heading should be in the next section</h1>
    </section>

    </main>

    </body>

CSS 的结构:

body {
    font-family: 'Lato', sans-serif;
    width: 100%;
    margin: 0 auto;
    display: grid;
    margin: 0 auto;
    grid-template-columns: 10% auto auto 10%;
    grid-template-rows: auto auto auto auto auto;
    grid-template-areas: "hero          hero          hero         hero"
                         "tech          tech          tech         tech"
                         "afford        afford        afford       afford"
                         ". .   .   ."
                         ". .   .   .";
    box-sizing: border-box;
    height: 100vh;
}

.hero {
    grid-area: hero;
    background-image: url('../images/people-working.jpg');
    width: 100%;
    height: 928px;
    background-size: cover;
    background-position: center;
}

.tech {
    grid-area: tech;
    width: 100%;
    height: 712px;
    position: absolute;
    text-align: center;
}

.afford {
    grid-area: afford;
    width: 100%;
    height: 832px;
    position: absolute;
    text-align: center;
}

【问题讨论】:

    标签: css layout grid


    【解决方案1】:

    如果删除位置:absolute;然后标记将被堆叠。我删除了此示例中的大部分代码,但我认为这是您在基本结构级别上的目标:

    http://codepen.io/stacy/pen/157042a40a8b4c23f1bad5c12719c8f5?editors=1100

    body {
        font-family: 'Lato', sans-serif;
        height: 100vh;
        display: grid;
        // grid-template-columns: 1fr;
        // grid-template-rows: auto;
        grid-template-areas: "hero"
                             "tech"
                             "afford";
        margin: 0 auto;
        width: 100%;
     }
    
    .hero {
        grid-area: hero;
    }
    
    .tech {
        grid-area: tech;
    }
    
    .afford {
        grid-area: afford;
    }
    

    如果您声明每个模板区域将填充的列数或声明 grid-template-columns 宽度,则不需要宽度。

    请记住,如果您将网格添加到正文,它不会应用于每个网格区域内的元素。希望有一天我们会看到 subgrid 规范变为现实,但在那之前,我们必须像使用 flexbox 一样应用它。到目前为止,我注意到您声明了 4 列并跨越了每个网格区域 4 次,这就是我提出这个问题的原因。

    希望这会有所帮助。

    【讨论】:

    • 谢谢。我没有意识到position:absolute 在其中扮演的角色,所以我将其删除,现在它可以工作了。
    猜你喜欢
    • 1970-01-01
    • 2014-01-18
    • 2019-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-15
    相关资源
    最近更新 更多