Vertically stack elements with absolute positioning using only CSS

Phi*_*ord 2 css

Maybe it's just late in the day but I can't figure this out even though it appears a relatively simple problem.

I have a simple jQuery function which is fired when a button is clicked. It creates elements and appends them to the body of my DOM:

$("#addBlock").click(function(){
    var $block = $("<div class='block'>I'm a block</div>");
    $("body").append($block);
});
Run Code Online (Sandbox Code Playgroud)

The .block class includes absolute positioning, like so:

.block {
    position: absolute;
    top: 10px;
    right: 10px;
    width: 200px;
    height: 50px;
    background-color: #A6201C;
    color: #fff;
}
Run Code Online (Sandbox Code Playgroud)

Each time the button is clicked a new .block element is successfully added. However, because of their absolute positioning they're "on top" of one another (in the z axis). What I want is for each element to appear beneath its previous sibling vertically (in the y axis).

I thought I'd be able to do this with a pseudo selector like :nth-of-type but I haven't actually been able to figure it out. I can achieve what I want if there are only two .block elements using the adjacent sibling combinator:

.block + .block {
    margin-top: 60px; /*The height of the previous block plus 10px for spacing*/
} 
Run Code Online (Sandbox Code Playgroud)

But that's no use because I don't know how many elements with this class there are going to be - it could be dozens.

Is there a way I can pull this off using CSS alone or will I need to modify my jQuery to accomplish it?

There's a fiddle of the example here.

Red*_*ams 5

与其尝试这样做,不如尝试将block元素添加到具有绝对位置的父div中:

$("#addBlock").click(function() {
  var $block = $("<div class='block'>I'm a block</div>");
  $("#blocks").append($block);
});
Run Code Online (Sandbox Code Playgroud)
body {
  background: #fff;
  padding: 20px;
}

#blocks {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 200px;
}

.block {
  height: 50px;
  background-color: #A6201C;
  color: #fff;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="addBlock">Add Block</button>
<div id="blocks">

</div>
Run Code Online (Sandbox Code Playgroud)