What is the best way to vertically center an element in this scenario without using JavaScript?

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:

  1. The parent has a fixed height with overflow-y set to auto.
  2. The child has a variable height, which can be less than or greater than the parent's height.
  3. 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.

Answer №1

After some experimentation, I have discovered the solution!

Try using the ":after inline-block" technique

.parent {
  width: 300px;
  height: 400px;
  text-align: center;
  overflow-y: auto;
  background-color: white;
}

.parent:after {
  display: inline-block;
  content: '';
  width: 0;
  height: 100%;
  vertical-align: middle;
}

.child {
  display: inline-block;
  width: 200px;
  height: auto;
  vertical-align: middle;
  text-align: left;
  background-color: grey;
}

See it in action: jsfiddle

Answer №2

To center your child element within its parent container, you can set a specific height and include the CSS property overflow: auto;. This will ensure that the text is contained within the child element only.

Check out this example

Answer №3

The issue lies in your usage of position absolute; instead, try using position relative and adjusting the margins on the left and right.

.child {
 position:relative;
 margin-left:auto;
 margin-right:auto;
 width: 200px;
 height: auto;
 background-color: grey;
}

For a working example, check out this Fiddle

If needed, you can also include top: 50%; or similar properties.

I hope this solution resolves your problem!

Answer №4

Desiring this :)

.parent {
  position: relative;
  width: 300px;
  height: 400px;
  overflow-y: auto;
  background-color: white;
}

.child {
  position: relative;
  top: 0%;
  left: 50%;
  width: 200px;
  height: auto;
  background-color: grey;
  transform: translateX(-50%);
}
<div class="parent">
  <div class="child">
    Et quinta decima eodem modo typi qui nunc nobis videntur parum clari fiant sollemnes in. Id quod mazim, placerat facer possim assum typi non habent claritatem insitam est usus. Dolor sit amet consectetuer adipiscing elit sed diam nonummy nibh euismod
    tincidunt ut laoreet? Gothica quam nunc putamus parum claram anteposuerit litterarum formas humanitatis per seacula quarta decima. Duis dolore te feugait nulla facilisi nam liber tempor cum soluta nobis eleifend. Nulla facilisis at, vero eros et accumsan
    et iusto odio dignissim. Demonstraverunt lectores legere me lius quod ii legunt saepius claritas est. Iriure dolor in hendrerit in vulputate velit esse molestie consequat vel illum dolore eu feugiat? Vel eum iriure dolor in hendrerit in vulputate
    velit esse molestie. Ex ea commodo consequat duis autem consequat vel illum dolore eu feugiat nulla. Augue duis dolore te feugait nulla facilisi nam liber tempor. Lectores legere me lius quod ii legunt saepius claritas. Litterarum formas humanitatis
    per seacula quarta, decima et quinta decima. Eorum claritatem Investigationes demonstraverunt est etiam processus dynamicus qui sequitur mutationem consuetudium lectorum mirum est! Minim veniam quis nostrud exerci tation ullamcorper suscipit lobortis
    nisl ut aliquip ex ea commodo consequat. Eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent.
  </div>
</div>

Answer №5

To ensure proper spacing, adjust the line-height of the child element.

.child { line-height: 400px; }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a custom design for a Bootstrap Modal using CSS styling

I have been working on a bootstrap modal that includes an image, and everything is functioning correctly. However, I am facing an issue with changing the styling of the button. Despite my attempts to modify the button's color by using its class in CS ...

jQuery Toggle and Change Image Src Attribute Issue

After researching and modifying a show/hide jQuery code I discovered, everything is functioning correctly except for the HTML img attribute not being replaced when clicked on. The jQuery code I am using: <script> $(document).ready(function() { ...

Aligning form fields in a HTML form using Bootstrap

In my extensive form, several fields within the setup encounter the same issue. Specifically, a checkbox below 'contact telephone number' causes the surrounding content to become misaligned. https://i.sstatic.net/8qI8Z.png My attempts to resolv ...

Utilize CSS to exclusively filter through items

Is it possible to use CSS alone to filter a list of items based on specific links being clicked? I have a list that should display only certain items when corresponding links are clicked. HTML: <!-- Header links --> <a href="#" class="all" tabin ...

Error encountered with the item properties in vue-simple-calendar 'classes'

For my Vue.js project, I am utilizing the npm calendar package called `vue-simple-calendar` and aiming to implement dynamic classes for each event item like background-color, etc. However, the `classes` property doesn't seem to be functioning as expec ...

Steps to deactivate a textarea in angularjs based on a selected option's value meeting a specific condition

Hello, I am a newcomer to AngularJS and I am looking to disable the textarea when a specific option is selected from a dropdown menu. I attempted to use ng-disabled="(here my ng-model value)" but unfortunately, it did not work as expected. If creating a ...

Choosing the initial offspring of an element that do not share a common parent

My question might not be perfectly phrased, for which I apologize. Is there a CSS method to select only the first child of an element without affecting others that are not grouped under the same parent? For instance: <div class="parent"> <div ...

How to center a text box within a div using CSS

Looking for equal margins on top and bottom? Here's how to achieve it: If you have a container div like this: <div id="search"> <input id="txtSearch" type="txt"> </div> Your CSS should look something like this: #search{ m ...

Creating a scrollable table body in Bootstrap 4

I am struggling to make a large table mobile-friendly using Bootstrap 4. The table can have up to 10 columns and 100 rows. I need a CSS solution that achieves the following: A fixed header with each column having the same width as its respective row An x/ ...

css and HTML tutorial: Centering a DIV element with CSS styles

I have exhausted all similar questions and solutions, but nothing seems to work for me. My goal is to center a DIV element using CSS, and I've tried options like text-align, margin auto, and inline-block with no success. The example code I am experime ...

What is the functionality of intro.js?

Currently, I am utilizing an onboarding tour at my.bonify.de that provides a similar experience to introjs. The way we have implemented this feature is quite unattractive, using a cutout div with a very large box-shadow. We are looking to enhance it by in ...

Design Shapes in Sketch with CSS Styling

Here is the CSS code I am working with: shadowColor: '#444', shadowOffset: { width: 5, height: 5 }, shadowOpacity: 0.2, shadowRadius: 8, backgroundColor: 'white', borderRadius: 10, I want to recreate this style in Sketch, but it uses ...

Jquery script to update the background of the parent element when Bootstrap Tabs

Currently, I am exploring ways to come up with a more sophisticated solution. However, my proficiency in jquery is somewhat limited at the moment. I believe there must be a more efficient method to achieve the desired function outlined below. In essence, ...

Perform the action as soon as the AJAX call is completed, without delaying the initiation of another AJAX call based on a set interval time

My webpage is experiencing slow retrieval of 10 images hosted on Amazon AWS. To improve loading speed, I am attempting to display a page without images and use AJAX calls to fetch them dynamically. The PHP script for fetching each image can take a long tim ...

Unable to update content within the `style` attribute when the HTML is stored in a variable

I am attempting to make changes to the style html - specifically by replacing a string, but unfortunately it is not functioning as expected. I am struggling to obtain the final updated html. Below is my attempt: var html = "<style>043BF83A8FB24A418 ...

Mastering the Art of Incorporating jQuery, JavaScript and CSS References into Bootstrap with ASP.NET WebForms

Hey there, I'm currently working on a personal project as a beginner in Bootstrap. My main challenge for the past two days has been trying to integrate a dateTimePicker and number Incrementer using Bootstrap techniques. Despite my efforts in researchi ...

The carousel in the Project file seems to be malfunctioning

Having previously utilized Owl carousel on my website, I made the switch to slick carousel for the slider on a NATA coaching center in Chennai. Unfortunately, I'm encountering issues with getting the slider to work and I'm unsure of where I may b ...

Troubleshooting CSS Display Problem on Chrome and Firefox

While working on the design of a website offline, everything seemed to be running smoothly. However, upon uploading it to the server, various issues began to arise. Initially, the file loaded correctly upon first visit. Unfortunately, after reloading the ...

Tips for creating vibrant tabs or incorporating additional outputText following tabs within primefaces

https://i.sstatic.net/vtipc.png In my tabView, I have two tabs and I am trying to add a third one that looks like the attached image. I have tried using outputText for this purpose, but it doesn't seem to work as expected. Specifically, I want part o ...

Troubleshooting Angular: Issues with Table Data Display and Source Map Error

I'm currently tackling a challenge in my Angular application where I am unable to display data in a table. When I fetch data from a service and assign it to a "rows" variable within the ngOnInit of my component, everything seems to be working fine bas ...