CSS视口高度:100vh与div中的内容不正确地工作

6

我是一名新手,注册是因为在现有的讨论中找不到我的答案。

我正在尝试制作一个单页网站,希望'落地页'具有全屏背景。我已经将背景放在整个页面上了,但当我开始在div中放置文本时,它就出问题了。我使用了以下css(sass):

.intro {
    color: #fff;
    height: 100vh;
    background: url('http://www.flabber.nl/sites/default/files/archive/files/i-should-buy-a-boat.jpg') no-repeat center center; 
    background-size: cover;

    &--buttons {
        position: absolute;
        bottom: 2em;
    }
}

p.hello {
    margin: 30px;
}

.page1 {
    color: #fff;
    height: 100vh;
    background: beige;
}

.page2 {
    color: #fff;
    height: 100vh;
    background: black;
}

使用以下HTML代码:
<html>
    <head>
        <link href="stylesheets/screen.css" media="screen, projection" rel="stylesheet" type="text/css" />
        <title>My title</title>
    </head>

    <body>
        <div class="container">
            <div class="row">

                <div id="intro" class="intro">

                    <div class="text-center">
                        <p class="hello">
                            Intro text is coming soon!
                        </p>
                            <div class="col small-col-12 intro--buttons">
                                <p>Buttons coming here.
                                </p>
                            </div>
                    </div>

                </div>

                <div id="page1" class="col col-12 page1">
                    <p>Tekst test</p>
                </div>

                <div id="page2" class="col col-12 page2">
                    <p>Tekst test.</p>
                </div>

            </div>
        </div>
    </body>
</html>

您可以在这里查看结果:http://codepen.io/Luchadora/full/waYzMZ 或者查看我的代码:http://codepen.io/Luchadora/pen/waYzMZ 正如您所看到的,当定位介绍文本 (p.hello {margin: 30px;}) 时,背景大小发生了变化,不再是全屏幕了。(顺便说一句:我使用了一个示例背景)。而且其他页面现在也有了白色空间。
我该怎么解决这个问题呢?我已经阅读了关于视口的文章,但我认为我只需要使用 height: 100vh;,对吗?谢谢!
3个回答

2
你的问题与 外边距折叠 有关: 父元素和第一个/最后一个子元素
如果没有边框、内边距、内联内容或间隙来分隔块元素的 margin-top 和其第一个子块元素的 margin-top,或者没有边框、内边距、内联内容、高度、最小高度或最大高度来分隔块元素的 margin-bottom 和其最后一个子块元素的 margin-bottom,则这些 margin 折叠。折叠的 margin 最终会出现在父元素之外。
要解决问题,请向 .text-center 添加一些内边距。
.text-center {padding:1px;}

更新的笔


谢谢,这个有效!最后我只是在具有背景的div('.intro'类)中添加了{padding:1px;},这也有效。至少,在我的桌面版本上是这样,但在Codepen示例中不是。但现在我有一个水平滚动条,而且overflow-x:hidden不起作用,我还在弄清楚那个问题。如果我将{padding:1px;}放在pintro div上,会有影响吗? - Luchadora
啊,好的。如果您设置了宽度并添加了填充,则填充将添加到宽度中(例如100%+ 2px)。为了解决这个问题,您可以添加box-sizing:border-box - 这意味着任何填充都将包含在宽度中。填充应该放在包装p的元素上(或其任何父级元素上)。 - Pete
感谢您提供的解决方案和解释!最终我在CSS中使用了overflow-x:hidden来修复它,作用于htmlbody两个元素。 - Luchadora

0

您尚未禁用页面主体的边距。请在您的CSS中添加以下内容:

body{
  margin:0px;
}

编辑:Pete发布的答案似乎是完整的解决方案,抱歉我太慢了!


-1

这在旁边的对话中已经提到过了,但这对我很有效,我希望大家能够轻松找到它。

-- overflow-x:hidden; on both html, body in the css.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接