html - 在 CSS 中使用最大宽度时如何制作灰色边距

标签 html css

我想要一个具有最大宽度和页脚的页面,如果窗口大于最大宽度,则将页边距设置为灰色以显示页面的主要部分。另外,我在底部有一个固定的页脚。

我将背景颜色设置为灰色,然后将主要内容的颜色设置为白色,并设置边距,除非主要 div 的高度不占用页脚的所有空间,否则我会得到在这个未使用的区域中有一大块灰色。

目标是为超过 1024 像素的空间设置灰色边距,一直到页脚,无论主 div 是否占据所有空间。

这是我的:

<style>
body {
    background-color: gray;
    max-width:800px;
    margin: 0 auto;
}
#main {
    background-color: white;
}
#footer {
    text-align: center;
    max-width: 800px;
    background-color: white;
    position: fixed;
    bottom: 0px;
    width: 100%;
    margin: 0 auto;
}
</style>
<div id='main'>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec mattis tortor a nisl rhoncus, vitae aliquet lectus sodales.
</div>
<div id="footer">Footer Goes Here</div>

这给了这个。您可以看到#main 和#footer 之间的灰色 Problem illustration

有什么建议吗?

最佳答案

如果我清楚地理解了您的要求,那么当width 大于800px 时,您希望在主要内容的左侧和右侧有灰色边距。您应该设置适当的主要内容高度。计算 viewport 高度并将其设置为主要内容高度。检查下面的代码或jsfiddle example .

body {
    background-color: gray;
    max-width:800px;
    margin: 0 auto;
}
#main {
    background-color: white;
   height: calc(100vh - 50px);
}
#footer {
    text-align: center;
    max-width: 800px;
    background-color: white;
    position: fixed;
    bottom: 0px;
    width: 100%;
    margin: 0 auto;
    height:50px;
}
<div id='main'>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec mattis tortor a nisl rhoncus, vitae aliquet lectus sodales.
</div>
<div id="footer">Footer Goes Here</div>

您可能希望更改页脚的高度,并相应地更改主要内容的 height 计算中的值。我将它设置为 50px 只是为了举例。

要测试它,请调整浏览器窗口的大小以查看灰色边距(如果您想在那里测试,jsfiddle 的浏览器部分也可以调整大小)。

注意 - 如果您还有以 px 为单位的标题高度,则您必须将该值也包括在主要内容的 height 计算中。

关于html - 在 CSS 中使用最大宽度时如何制作灰色边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47342570/

相关文章:

html/css : how to on a single line center "title" and have on right buttons

css - 纯 CSS 三 Angular 形在 Firefox 中看起来很模糊

html - 将表单元素移动到它们看起来堆叠的位置

javascript - 如何检查父元素的 css 样式?

javascript - 在文本区域中输出图像

html - 我怎样才能最好地将基于框架的 "HTML of yesteryear"应用程序移植到现代 CSS(3)?

html - CSS - css 的大小是否影响页面呈现

javascript - 使用图像渲染 : pixelated; causes moving image to ripple a vertical pixel line

javascript - 动态附加元素时避免在 jquery 中内联样式吗?

c# - 你能在 ASP.net 2.0 中通过 CSS 或皮肤设置页面的标题吗