Absolutely positioned elements collapse

I have some absolutely positioned elements:

CSS

span {
  display: block;
}

span.sub {
  color: blue;
  position: absolute;
}

HTML

<div>
  <span>Coffee</span>
  <span class="sub">Tea</span>
  <span class="sub">Milk</span>
  <span class="sub">Water</span>
</div>

DEMO

How can I prevent them from collapsing? I want them to flow freely over the elements under div , like a dropdown navigation menu. Can it be achieved without nesting the positioned elements inside an extra container?

The thing about absolute positioning is, it takes the elements out of the document flow.

Yes, by explicitly defining a position for each element with the top property.
Though making a wrapper that has absolute positioning and displaying the subs as ordinary blocks within it is probably better.

.sub:nth-child(3) {
  top: 2.8em;
}
.sub:nth-child(4) {
  top: 4em;
}
2 Likes

Yes it can be achieved but will require magic number fixes and non semantic html. Why the limitation on the html unless you are just playing around?

In Sam’s example above to you would need to add a top position to all the sub items in order to line them up under each other,. It may be simpler if you have more than a few items instead to just limit the height of the div and then all the elements below will overflow as though they were absolutely placed without actually needing to place them absolutely.

e.g.

div {
  height: 1.5rem;
  background: red;
  line-height: 1.5rem;
}
span {
  display: block;
}
span.sub {
  color: blue;
  background: rgba(0, 0, 0, 0.6);

}

That requires only one magic number fix in the height added to the div. Where possible magic numbers should be avoided.

1 Like

But they won’t look good: demo.

I’m not sure I see your point? That’s more or less what you asked for.

You asked how to have the elements flow freely over content below and I showed you how to do it.

It’s up to you to style them as you wish as you gave no example of the effect you want to achieve.

If you have a design in mind then it would help if you let us know what it should look like :slight_smile:

With a few tweaks here it is as a dropdown on hover of ‘Coffee’.

Same method though.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.