There are two components: a parent (white box) and a child (grey box). My goal is to center the child vertically within the parent.
These are the three constraints:
- The parent has a fixed height with overflow-y set to auto.
- The child has a variable height, which can be less than or greater than the parent's height.
- The child is a regular component (div), not just an image or paragraph of text.
Due to the variable height of the child, I opted to use "absolute position + translate" to achieve this effect. Here is the CSS code snippet:
.parent {
position: relative;
height: 400px;
width: 300px;
overflow-y: auto;
}
.child {
position: absolute;
top: 50%;
left: 50%;
width: 200px;
height: auto;
transform: translate(-50%, -50%);
}
This method works well when the child's height is less than that of the parent.
If the child's height exceeds the parent's height, issues arise as shown in picture (b) below. The problem seems to be related to the "translate-y" property causing the child to be cropped.
You can view a live demo here.
How can I resolve this issue? Is there a better approach to achieve this layout?
Click here to see the image.