【问题标题】:make width of a div equal to width of the screen, regardless of the width of its containing div [closed]使 div 的宽度等于屏幕的宽度,无论其包含 div 的宽度如何 [关闭]
【发布时间】:2014-05-09 22:25:52
【问题描述】:

我有两个 div:

<div id="container">
  <div id="content">
    I want this div to take the width of the browser!
  </div>
</div>

#container div 的宽度大于屏幕宽度。我希望 div #content 占用浏览器的宽度。我正在使我的网站具有响应性,当手机处于正常位置时,浏览器大小为 320,水平时为 480。我希望 #content 响应地改变宽度。

我该怎么做?谢谢

编辑

我认为我不能使用 css。我应该在前面解释过,但是在css中使用绝对定位的问题是我需要保持#content的相对位置,容器是一个包含3个#content div的滑块。当我用手指滑动时,我希望活动 div 占据屏幕的宽度。所以我真的不能用绝对定位!

【问题讨论】:

  • 宽度为 9000 ?笏...为什么?
  • 谁在乎,假设性地说
  • 你永远不需要那样的东西

标签: jquery html css responsive-design


【解决方案1】:

尝试使用:

$(window).resize(function() {
    $('#content').width($(this).width());
}).resize();

【讨论】:

  • 这不是永久循环吗?
  • 我应该把它放在 $(document).ready(function(){ }); ?
  • .resize(); 没有必要
  • 我觉得你应该提到用 javascript 修复显示或样式问题通常是不好的做法,除非没有其他方法
  • @mohamedrias 因为您的回答实际上并没有解决 OP 的问题。
【解决方案2】:

到底为什么#content 的宽度是 9000?听起来可能有更好的方法来实现您的设计。

也就是说,以下将起作用:

Demo Fiddle

HTML

<div id="container">
    <div id="content">I want this div to take the width of the browser!</div>&nbsp;
</div>

CSS

html, body {
    width:100%;
    margin:0;
    padding:0;
    position:relative;
}
#container {
    width:9000px;
}
#content {
    position:absolute;
    width:100%;
    background:red;
}

【讨论】:

  • 这个解决方案的问题是我需要保持#content的相对位置,容器是一个包含3个#content div的滑块。当我用手指滑动时,我希望活动 div 占据屏幕的宽度。所以我真的不能用绝对定位!
  • @user3618369 - 由于 CSS 的级联性质,您将无法做到这一点。你要么需要使用 JS(丑陋),要么重新考虑你的布局。
【解决方案3】:

您想在 CSS 和 HTML 中执行此操作。

首先,在 html 中使用视口。

<meta name="viewport" content="width=device-width, user-scalable=no">

然后在 css 中使用:

body{
width:100%;
overflow:hidden;
}

#container{
width:9000px; 
height:200px;
overflow-x:scroll;
overflow-y:hidden;
}

附带说明 - 为什么您的容器是 9000 像素?

将您的 CSS 隐含为流动结构而不是设置宽度始终是最佳实践 - 因此请尝试以下方法:

#container{
width:100%;
overflow-x:scroll;
overflow-y:hidden;
}

#content {
width:auto;
height:100%;
}

假设您正在寻找一个完全宽度的可滚动内容。

【讨论】:

  • 请插入正确的 css 选择器。根据问题,他们俩都是错误的
  • 这是一个写作选择,不是一个确定的东西 - 如果他想使用 ID,让他使用它们,只要它们没有重复 - 他仍然有权使用。
【解决方案4】:

您可以在CSS 中使用position:absolute#content 执行此操作,然后设置宽度,在本例中为100%:

#content { position: absolute; width: 100%; }

SEE FIDDLE

但是,这只有在它的父元素都没有position:relative 时才有效。如果他们这样做,我会使用 Felix 的答案

【讨论】:

  • 小提琴不能代替将代码放入答案中。
  • @Liam 但是您在我的答案中输入的代码与答案无关
  • 这是你的小提琴代码?!
  • @jumpingcode 也许从你的小提琴中粘贴其余部分是要走的路吗?
  • @jumpingcode 啊我明白了,刚刚查看了编辑。这里没什么可看的,继续前进……
【解决方案5】:

Working demo

可以使用 CSS 本身来完成:

#content {
    width: 100%;
}

如果你想根据屏幕分辨率自定义背景和其他属性,那么媒体查询是最好的选择

@media (max-width: 480px) {
   #content {
        width: 480px !important;
  }
}
@media (max-width: 30px) {
   #content {
        width: 480px !important;
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 2018-09-03
    • 2013-03-29
    • 1970-01-01
    • 2022-12-14
    • 2012-11-04
    相关资源
    最近更新 更多