Align a 'div' in the middle of a percentage height 'div' vertically

Can a div be vertically centered within a parent div with a percentage height?

Answer №1

This question has been asked numerous times on various platforms across the web.

A simple search will yield plenty of results. Personally, I prefer using display: table-cell; and vertical-align: middle; to achieve this. Check out an example at this link. (Note that this method may not be compatible with Internet Explorer 6.)

Answer №2

In the scenario where your inner div has a fixed height, say 100 pixels, one way to handle it is as follows:

.container{
  position: relative; // Can also use absolute or fixed
  height: 80%;
}

.child{
  position: absolute;
  width: 100px;
  height: 100px;
  top: 50%;  // Initially at 50%, may not be centered
  margin-top: -50px; // Adjusting to align properly
}

Although this solution is effective, there are alternate methods like utilizing tables or display: table-cell;. This is just one approach that comes to mind...

Answer №3

.container {
  display: table-cell;
  vertical-align: middle;
}

Caution - compatibility may vary among different browsers!

Answer №4

Avoid using px units for better flexibility.

Instead of specifying top, bottom, right, left in pixels, consider using percentages:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Add your title here</title>
    </head>

    <body>
        <div style="position: absolute;
                    top: 0;
                    bottom: 0;
                    right: 0;
                    left: 0;
                    text-align: center;
                    white-space: nowrap;
                    overflow: hidden;">
            <div style="position: relative;
                        display: inline-block;
                        height: 100%;
                        vertical-align: middle;"></div>
            <div style="background-color: #FEEF88;
                        position: relative;
                        display: inline-block;
                        vertical-align: middle;">Hello world! :D</div>
        </div>
    </body>
</html>

Answer №5

My preferred technique involves utilizing two containers for better organization:

The outer container:

  • Ensure the outer container has display: table;

The inner container:

  • The inner container should have display: table-cell;
  • It should also include vertical-align: middle;

The content box:

  • Use display: inline-block; for the content box

You are free to add any desired content to the content box without worrying about its dimensions!

To center horizontally, simply apply text-align: center; to the inner container.

Live Demonstration:

body {
    margin : 0;
}

.outer-container {
    position : absolute;
    display: table;
    width: 100%;
    height: 100%;
    background: #ccc;
}

.inner-container {
    display: table-cell;
    vertical-align: middle;
}

.centered-content {
    display: inline-block;
    background: #fff;
    padding : 20px;
    border : 1px solid #000;
}
<div class="outer-container">
   <div class="inner-container">
     <div class="centered-content">
        Malcolm in the Middle
     </div>
   </div>
</div>

For a visual representation, check out this Fiddle example!

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

Retrieve text from all the spans within a specific div and present it in a formatted list

Seeking assistance to extract and display the content of spans within my data as a list. Any help would be greatly appreciated. Thanks. let container = $("#article-content"); let spans = container.find(".footnote"); let outputP = $("#footnotes"); fo ...

Close the ionicPopup by tapping anywhere

Currently, I have implemented an ionicPopup that automatically closes after a certain time limit. However, I am wondering if there is a way to configure it to close with a single or double tap anywhere on the screen instead. While I am aware that setting a ...

Issues with scrollspy functionality in Bootstrap 4 beta

Although similar to this question, I'm facing a different issue. The solution provided there involves manually writing JavaScript code to highlight active links on scroll, while I am trying to use the scrollspy plugin. I've reviewed various othe ...

What is the best way to get three columns of images to align in a single row?

I'm currently working on setting up a portfolio section for a website I am developing using Bootstrap. Unfortunately, I've run into an issue where the third item in my lineup keeps jumping to the next line and I can't figure out how to fix ...

The way Chrome interprets the CSS class height and width attributes for input tags can vary

I was working on developing and testing a section of HTML div when I encountered an issue. After placing that section in another HTML page, the input tag CSS appeared to be rendered differently. This led me to enter debug mode. Interestingly, the CSS box ...

Activate a hyperlink from a distance

I have a side menu that includes a form for logging out (generated by MVC). Is there a way to set it up so that when the user clicks on the <li> element, it automatically triggers the log out link? I'm curious if using inline Javascript or anot ...

Setting the thumbnail image for an HTML5 video: A step-by-step guide

Is it possible to set a thumbnail image for an HTML5 video? I would like to display an image before the video starts playing. Here is my current code: <video width="470" height="255" controls> <source src="video.mp4" type="video/mp4"> ...

Create dynamic and interactive content by embedding text within SVG shapes using the powerful D

How can I write text into an SVG shape created with d3.js and limit it to stay inside the shape similar to this example http://bl.ocks.org/mbostock/4063582? I attempted to use a clipPath following the example provided. However, when inspecting with firebu ...

The @Html.Label feature fails to appear when the content includes a period (.) - Utilizing Bootstrap with MVC Razor

I am dynamically populating label text from a database source <div class="col-11 col-sm-11 col-md-11 col-lg-11 col-xl-11"> @Html.Label(@Model.Questions[i].DataText + ": ", new { @for = "dd" + @Model.Questions[i].Data ...

Can a Django form be configured to hide submitted values using display:none?

As I was working on submitting a form in Django with multiple details, I came up with the idea to split it into sections. The first set of details would be hidden initially, and upon clicking the next button, the next set of details would be displayed fo ...

Ways to modify the appearance of an element using a targeted CSS class

I am attempting to customize the font-family of a specific element on a website (https://chromewebstore.google.com/) with my own custom font. To achieve this, I created a Chrome extension locally. However, the element I want to modify does not have an "id" ...

Stop access to geojson files through targeted media queries

Using a vue.js app, I have the ability to choose locations using either a map or an input field. However, for mobile users, I want to exclude the map and only serve the search engine. The issue is that it's not very user-friendly on mobile devices be ...

Tips for including HTML tags in strings without causing issues with nested tags

I am struggling with a string that contains both text and HTML tags, specifically <a href=""></a> tags. My goal is to apply the "i" tag around the text outside of the "a" tags without creating nested tags like: <i><a href=""></a ...

Mobile Device Experiencing Constant Resizing Issues on Website

I have been working on my website for almost a year now, and I am facing an issue with its responsiveness on mobile devices. Despite using Bootstrap 4 and Ajax to load pages and modals, I can't seem to figure out what's causing the problem. Befor ...

Unable to stack a text element on top of another element with CSS

I am a novice looking to delve into the world of programming. Currently, I am immersing myself in learning HTML and CSS while embarking on my inaugural project. The task at hand involves creating a simple homepage for a local game store with the objective ...

Is it possible to load a webpage in a WebBrowser control without displaying certain HTML elements by their IDs

Is there a way to load a specific page using the WebBrowser control without displaying unwanted advertisement banners in the 'tb' DIV element? I've searched online and came across an example that uses the mshtml reference, but I can't ...

What is the best way to merge various sass directories into a single css file?

I have a situation where I need to compile two separate scss directories into a single css output file. When compiling a single directory, I would use the following command: sass --watch scss/template.scss:css/template.css Is there a way to combine two d ...

Learn how to retrieve images from the web API at 'https://jsonplaceholder.typicode.com/photos' and showcase them on a webpage using Angular10

Using the API "https://jsonplaceholder.typicode.com/photos", I have access to 5 properties: albumId: 1 id: 1 thumbnailUrl: "https://via.placeholder.com/150/92c952" title: "accusamus beatae ad facilis cum similique qui sunt" url: "https://via.placeh ...

Tips for displaying a fallback image when the desired image is not found in HTML 5

Is there a way to display a default image indicating that the image is not found when one of the images on the page cannot be loaded? If so, how can it be implemented? ...

Trouble with Bootstrap 5 Carousel swipe functionality: Issues arise when inner elements with overflow are involved, causing vertical scrolling to interfere with left to right swipes

I've been scouring the internet for answers to my unique issue with a Bootstrap 5 carousel. My setup is fairly basic, but I've removed the buttons and rely solely on swiping to navigate through the carousel items. When I swipe left to right, eve ...