CSS宽度100%仅限于浏览器窗口(它不会扩展到右侧滚动区域)

问题描述 投票:4回答:3

此站点是全宽度的,并且适应浏览器窗口的大小。但是,一旦浏览器窗口小于显示的内容,一旦向右滚动,标题就会被切断。

默认宽度100%似乎只适用于浏览器窗口的宽度,而不是页面的宽度!同样似乎也适用于垂直轴。


Example

#title
{
  height: 50px;
  color: white;
  background-color: #404040;
}
#content
{
  width: 800px;
  background-color: #f0f0f0;
}
<div id="title">
    TITLE
</div>
<div id="content">
    CONTENT
</div>

Actual result

这是页面向左滚动时的样子

1

2

(为了简单和隐私,与问题无关的内容会受到审查。)

html css width
3个回答
2
投票

在摆弄了很多定位之后,我最终想出了一些东西。

body
{
    position: absolute;
    min-width: 100%;
    min-height: 100%;
}

#menu-background
{
    z-index: -1;
    position: absolute;
    width: 250px;
    height: 100%;
    background-color: #404040;
}

和菜单背景HTML

<div id="menu-background"></div>

<body>需要绝对定位,否则内容div的表将溢出内容div。此外,它需要100%的min-width来涵盖两种情况:窗口较小,或者较大。

菜单的工作方式相同,只是它是一个横跨整个页面的单个<div>


此解决方案适用于X和Y(菜单和标题)拉伸和背景颜色。


1
投票

很明显,width: 100%占据了窗口的宽度,但不是文档的宽度。

据我所知,这个行为在规范中并不完全清楚。

10.2 Content width: the width property

<percentage>

指定百分比宽度。百分比是根据生成的框的包含块的宽度计算的。如果包含块的宽度取决于此元素的宽度,则在CSS 2.1中未定义结果布局。


围绕该问题的两种方法涉及CSS定位。

1. position: fixed

固定定位使宽度相对于视口。

#title { 
  height: 50px;
  color: white;
  background-color: #404040;
  position: fixed; /* NEW */
  width: 100%; /* NEW */
}

DEMO

2. position: absolute

绝对定位也有效:

#title {
  height: 50px;
  color: white;
  background-color: #404040;
  position: absolute;
  width: 100%; 
}

DEMO


0
投票

对我来说,它与这两个小朋友一起工作:

width: auto;
min-width: 100%;

不需要positon: fixed/absolute

© www.soinside.com 2019 - 2024. All rights reserved.