Imam Bux
Imam Bux

Reputation: 1166

absolute div inside absolute div cuts off with respect to relative position

I have 3 divs on top of each other having following css.

.d1 {
    position: relative;
    background-color: yellow;
    height: 50px;
    width: 100px;
    overflow: hidden;
}

.d2 {
    position: absolute;
    background-color: green;
    height: 25px;
    width: 50px;
}

.d3 {
    position: absolute;
    left: 83px;
}

and the divs that have classes are as follows:

<div class="d1">
  <div class="d2">
    <div class="d3">text</div>
  </div>
</div>

and as a result I see content of d3 cut off because of overflow:hidden in d1.

enter image description here

How can I avoid cut off content of d3 without modifying d1?

Upvotes: 2

Views: 2585

Answers (1)

Eric Snover
Eric Snover

Reputation: 21

Getting around the overflow

An element can overflow from a relative or absolute positioned parent by setting its position to fixed. An element that has position: fixed will have the default left,right,top, and bottom styles set as auto. This will position .d3 to the top-left of .d2, and then the left: 83px style will push it to the left from there.

Making up the additional space

However, to get that additional movement to the right as the original markup, you will need to add margin-left: 8px, which will make-up the additional ~8px needed to replicate the original. Further adjustments to the position of .d3 will need to be done by setting the margin style (see below).

Your updated code should look like this

.d1 {
   position: relative;
   background-color: yellow;
   height: 50px;
   width: 100px;
   overflow: hidden;
}

.d2 {
  position: absolute;
  background-color: green;
  height: 25px;
  width: 50px;
}

.d3 {
 position: fixed;
 margin-left: 8px;
 left: 83px;
}
<div class="d1">
  <div class="d2">
    <div class="d3">text</div>
  </div>
</div>

Some considerations and caveats

As a previous commenter mentioned, best practice would be to fix your HTML markup because this solution could cause issues if you ever need to move the position of .d3. For example, setting left, right, top, or bottom will cause the default setting of this style, auto, from being unset, and the element will be positioned relative to the viewport rather than the parent relative or absolute element.

Upvotes: 2

Related Questions