简体   繁体   中英

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. 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. Any of the overflow from Stage will be hidden, so you will only be able to see the 3 elements.

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). I can't inherit the Element's parent's width since that will be larger as the amount of containers.

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% ? Right now, Slider is position: absolute and width: 500% with Stage being position relative .
  2. Can Element be a 3rd, 4th, or some percentage of Stage without the use of Javascript or hardcoded values?

Lack of support for IE is perfectly fine and preferably without the use of JS for resizing/calculating widths.

Demo of what I have.

Change the display of slider to table and treat each element as 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:

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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