'width as percent of offsetParent

Is there a pure CSS solution to specify the width of an element to be a percent of the offsetParent?

I have to provide a piece of HTML as a template which is rendered multiple times within a container. The template I provide itself is wrapped into another div element before placing into the container and I don't have an option to modify either the container or the wrapper. I can only provide the HTML template.

The final HTML structure would look like

<html>
    <body>
        <div style="display:flex;flex-wrap:wrap;position:relative;"> <!-- container -->
            <div> <!-- wrapper -->
                <div style="width:20%;"> <!-- template -->
                    Hello world 1
                </div>
            </div> 
            <div> <!-- wrapper -->
                <div style="width:20%;"> <!-- template -->
                    Hello world 2
                </div>
            </div>
        </div>
    </body>
</html>

I am looking for a way to tell this template to occupy a percent of the container, not the wrapper.

css


Solution 1:[1]

Instead width: 20% you can use width: 20vw;.

with width vw

.container {
  display:flex;
  flex-wrap:wrap;
  position:relative;
}
.ch {
  background: gray;
  padding:20px;
  width: 20vw;
  border: 1px solid black;
}
<html>
    <body>
        <div class="container"> <!-- container -->
            <div> <!-- wrapper -->
                <div class="ch ch1" > <!-- template -->
                    Hello world 1
                </div>
            </div> 
            <div> <!-- wrapper -->
                <div class="ch ch2"> <!-- template -->
                    Hello world 2
                </div>
            </div>
        </div>
    </body>
</html>

with width %

.container {
  display:flex;
  flex-wrap:wrap;
  position:relative;
}
.ch {
  background: gray;
  padding:20px;
  width: 20%;
  border: 1px solid black;
}
<html>
    <body>
        <div class="container"> <!-- container -->
            <div> <!-- wrapper -->
                <div class="ch ch1" > <!-- template -->
                    Hello world 1
                </div>
            </div> 
            <div> <!-- wrapper -->
                <div class="ch ch2"> <!-- template -->
                    Hello world 2
                </div>
            </div>
        </div>
    </body>
</html>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1