简体   繁体   English

将元素的宽度设置为其祖父母的百分比

[英]Set an element's width to a percentage of its grandparent

在此处输入图片说明 * not drawn to scale * 未按比例绘制

I've been trying to come up with some CSS to achieve what I am depicting in this picture. 我一直在尝试提出一些CSS来实现我在这张照片中所描绘的。 Where I have a Stage which defines the size of what is visible and a Slider element which contains all of the elements so you can scroll/slide between elements. 在这里,我有一个定义可见大小的舞台和一个Slider元素,其中包含所有元素,因此您可以在元素之间滚动/滑动。 Any of the overflow from Stage will be hidden, so you will only be able to see the 3 elements. Stage中的任何溢出都将被隐藏,因此您将只能看到3个元素。

What I'm trying to figure out is if there's a way to define an Element's width as a third of the Stage (x/3 and x in this picture). 我要弄清楚的是,是否有一种方法可以将元素的宽度定义为舞台的三分之一(此图中的x / 3和x)。 I can't inherit the Element's parent's width since that will be larger as the amount of containers. 我不能继承Element的父级宽度,因为它的宽度会随着容器的数量而变大。

Now, I have two questions regarding this. 现在,我有两个问题。

  1. How I can make Slider adjust it's width automatically without setting it to a value like 500% ? 如何使Slider自动调整其宽度而不将其设置为500%类的值? Right now, Slider is position: absolute and width: 500% with Stage being position relative . 现在,Slider position: absolutewidth: 500% ,而Stage则是position relative
  2. Can Element be a 3rd, 4th, or some percentage of Stage without the use of Javascript or hardcoded values? 在不使用Javascript或硬编码值的情况下,Element可以是Stage的3%,4th或某个百分比吗?

Lack of support for IE is perfectly fine and preferably without the use of JS for resizing/calculating widths. 缺少对IE的完美支持,最好不使用JS来调整/计算宽度。

Demo of what I have. 我所拥有的演示

Change the display of slider to table and treat each element as table-cell . 将滑块的display更改为table ,并将每个元素视为table-cell
And provide min and max width of element to one constant value. 并将元素的最小和最大宽度提供给一个常数。

Pen Here 笔在这里

<div class="stage">
  <div class="slider">
    <div class="element"></div>
    <div class="element"></div>
    <div class="element"></div>
    <div class="element"></div>
    <div class="element"></div>
  </div>
</div>

CSS: CSS:

body {
  background-color: grey;
}

.stage {
  background-color: purple;
  height: 500px;
  margin: 0 auto;
  overflow: scroll;
  position: relative;
  width: 800px;
}

.slider {
  position: relative;
  display: table;  
  border-spacing: 20px;
}

.element {
  background-color: darkcyan;
  display:table-cell;
  height: 300px;
  min-width:300px;
  max-width:300px;
}

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

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