简体   繁体   English

CSS:给出与“祖父母”元素相同宽度的元素

[英]CSS: give element same width as “grandparent” element

I have a supercontainer (fitting screen width, with margins and padding) , which contains a wider container, which in turn contains (sorry for the redundancy) an undetermined (DB-driven) number of left-floated boxes. 我有一个超级容器(适合屏幕宽度,有边距和填充),其中包含一个更宽的容器,而容器又包含(对于冗余而言)未确定(DB驱动)的左浮动框数。 It is all part of a Backbone/Underscore template. 它是Backbone / Underscore模板的所有部分。

I want the boxes to have the same width as the supercontainer, in order to make only one visible at a time (there's a horizontal scroller-function in the Backbone View). 我希望盒子的宽度与超级容器的宽度相同,以便一次只能看到一个(在Backbone View中有一个水平滚动功能)。 I know I could use jQuery to get the supercontainer's width and apply it to boxes upon rendering, but I would definitely prefer a pure-CSS solution to avoid issues with screen resizing. 我知道我可以使用jQuery获取超级容器的宽度并在渲染时将其应用于盒子,但我绝对更喜欢纯CSS解决方案以避免屏幕大小调整的问题。

To make things clear: 为了清楚起见:

HTML: HTML:

<div id="supercontainer">
  <div id="wide-container">
    <div class="fun-box"></div>
    <div class="fun-box"></div>
    <div class="fun-box"></div>
  </div>
</div>

CSS: CSS:

#supercontainer {
  width:100%;
  overflow:hidden;
  margin:50px;
}

#wide-container {
  display:table;
}

.fun-box {
  height:100%;
  float:left;
  width: ???; /* something that makes it as wide as the supercontainer */
}

How can I do that? 我怎样才能做到这一点?

If the #supercontainer always has 100% width of window, you can match it by applying width: 100vw for the boxes 如果#supercontainer始终具有100%的窗口宽度,则可以通过应用width: 100vw来匹配它width: 100vw用于框

.fun-box {
  height:100%;
  float:left;
  width: 100vw; 
}

Viewport-percentage lengths defined a length relatively to the size of viewport, that is the visible portion of the document. 视口百分比长度定义了相对于视口大小的长度,即文档的可见部分。

1vw =1/100th of the width of the viewport 1vw =视口宽度的1/100

- MDN - MDN

You can try making .fun-box a third of #wide-container 's width, and #wide-container three times #supercontainer : 你可以尝试使.fun-box的三分之一#wide-container的宽度,和#wide-container三次#supercontainer

#wide-container {
    width: 300%;
}
.fun-box {
    width: 33.33%;
}

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM