Html 设置 div 宽度等于窗口大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20762823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 00:10:54  来源:igfitidea点击:

Set div width equal to window size

htmlcsswidth

提问by Ruthreshwar

I have a container of width 1300 px. Inside the container i have other div.
I need to set the inner div width equal to browser window size eg) 1900px.
The content should be responsive to the window size.

我有一个宽度为 1300 像素的容器。在容器内我有其他 div。
我需要将内部 div 宽度设置为等于浏览器窗口大小,例如)1900px。
内容应响应窗口大小。

My html code is like below:

我的 html 代码如下:

<div class="container">
  <div class="content">Some style goes here </div>
</div>

Css:

css:

.container {
   width: 1300px;
} 

.content{
  width: 100%
}`

回答by Rijin Mk

If you have the div width in pxformat it wont be responsive. It has to be in %format. If you put the inner content as width:100%The inner content will have a width of the '.container'.
So in order to get the inner div to be the window width you should have the .containerto be equal to the window width.

如果您有px格式的 div 宽度,它将不会响应。它必须是%格式。如果您将内部内容设置为width:100%内部内容,则其宽度为“.container”。
因此,为了使内部 div 成为窗口宽度,您应该使 div.container等于窗口宽度。

CSS:

CSS:

.container{
   width:100%;
}

Or if you want we can use jQuery:

或者,如果您愿意,我们可以使用 jQuery:

 var w = $(window).width();
 $('.content').css('width', w);

回答by sachinjain024

It looks like you want to open your contentdiv as a modal window, hiding rest of the body elements. Try this JSBIN DEMO

看起来您想将contentdiv 作为模态窗口打开,隐藏其余的 body 元素。试试这个JSBIN 演示

.content {
  position: fixed;
  top: 0;
  left: 0;
  bottom:0;
  right:0;
}

回答by CRABOLO

change container to

将容器更改为

.container {
   width: 100%;
}

回答by NoobEditor

With a fixed width: 1300px;, you can not have a responsive to the window sizediv

使用 fixed width: 1300px;,您不能有responsive to the window sizediv

As codehorse said, add

正如codehorse所说,添加

.container {
   width: 100%;
}

but add

但添加

html, body {
    height:100%;
    width:100%;
    margin:0;
    padding:0;
}

to you css as width: 100%;will render correctly if the dimension of the parent elements have been set beforehand!!

width: 100%;如果事先设置了父元素的尺寸,css as将正确呈现!

working demo

工作演示