Martin Braun
Martin Braun

Reputation: 12569

How to position absolute in within nested relative containers?

I'm using Ant Design for my website frontend, a similar framework like Bootstrap for React JS, but not really relevant here, since this is a pure CSS question.

The framework uses rows and columns that are relative. Now I want to overlay the parent element with an absolute element that is nested deep inside in it. I don't want to change the CSS of the rows or columns and I don't want to move the absolute container outside of my nested elements.

Is this possible, if so, how?

.row { /* copied from Antd */
  position: relative;
  height: auto;
  margin-right: 0;
  margin-left: 0;
  zoom: 1;
  display: block;
}

.col { /* copied from Antd */
  flex: 0 0 auto;
  float: left;
  position: relative;
  min-height: 1px;
  padding-right: 0;
  padding-left: 0;
}

.test {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: #333;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <div>This line should stay visible.</div>
  <div class="row">
    <div class="col">
      <div>Right below this line it should be darken:
      <div class="row">
        <div class="col">
          <div class="test"></div>
        </div>
      </div>
    </div>
  </div>
</body>
</html>

The desired effect looks like this, but I'm unsure if this is really possible:

preview

The test container should start where its parent column starts, but be greedy. Is this even possible? I have no problems to add more divs around the test container, though.

Upvotes: 0

Views: 997

Answers (1)

Temani Afif
Temani Afif

Reputation: 272648

Make the absolute element big enough and hide the overflow where you want:

.row {
  /* copied from Antd */
  position: relative;
}

.col {
  /* copied from Antd */
  position: relative;
}

.test {
  position: absolute;
  top: -100vh;
  right: -100vw;
  bottom: -100vh;
  left: -100vw;
  background: rgba(0, 0, 0, 0.8);
  z-index: 2;
}
<div>This line should stay visible.</div>
  <div class="row">
    <div class="col">
      <div>Right below this line it should be darken:
      <div class="row" style="overflow:hidden"> <!-- hide here -->
          dark content here
        <div class="col">
          dark content here
          <div class="test"></div>
        </div>
      </div>
    </div>
  </div>

Upvotes: 1

Related Questions