How to make a child component visible outside its parent that has overflow:hidden
Updated:
The short answer is it’s impossible.
The purpose of an overflow
with a value hidden
is to hide any content that overflows outside its parents.
Problem
In my initial setup, I had a parent div with overflow:hidden
to clip the image in rounded
corners with a relative
position.
What I also want is to have a dropdown component on top of the image, so I set an absolute
position to the dropdown like this 👇
Note: To make the code easier to read, I only show the relevant code and not all of the styling.
<div class="wrapper">
<!-- Image -->
<div>
<img src="./my-image.jpg">
</div>
<!-- Dropdown -->
<div class="dropdown">
<form>
<select>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</form>
</div>
</div>
.wrapper {
position: relative;
overflow: hidden;
border-radius: 1rem;
}
.dropdown {
position: absolute;
inset: 0;
}
Or if you prefer seeing it in Tailwind CSS. Notice that the overflow-hidden
class is on the parent
element as highlighted.
<div class="relative rounded-2xl overflow-hidden">
<!-- Image -->
<div>
<img src="./my-image.jpg">
</div>
<div class="absolute inset-0">
<!-- Dropdown -->
<form>
<select>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</form>
</div>
</div>
Here is the result
As you see, the dropdown element isn’t visible outside the image, I have to scroll down to see all the dropdown options.
This is caused by a class of overflow:hidden
on the parent element, therefore all
of its children will not be visible outside the parent element.
Solution
The solution is to change the structure of HTML by taking the child dropdown element outside of overflow: hidden
parent by making it a sibling to an overflow: hidden
element.
Below is HTML and CSS structure. Notice that overflow: hidden;
is now on <div class="image-wrapper">
instead of <div class="wrapper">
.
<div class="wrapper">
<!-- Image -->
<div class="image-wrapper">
<img src="./my-image.jpg">
</div>
<!-- Dropdown -->
<div class="dropdown">
<form>
<select>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</form>
</div>
</div>
.wrapper {
position: relative;
}
.image-wrapper {
overflow: hidden;
border-radius: 1rem;
}
.dropdown {
position: absolute;
inset: 0;
}
This is an equivalent in Tailwind CSS.
<div class="relative">
<!-- Image -->
<div class="rounded-2xl overflow-hidden">
<img src="./my-image.jpg">
</div>
<div class="absolute inset-0">
<!-- Dropdown -->
<form>
<select>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</form>
</div>
</div>
Here is the result, Drum roll 🥁 🥁 🥁 ….
The dropdown is now visible outside the image and I don’t have to scroll down to see all the options like before.