Center a single div vertically within a parent div by utilizing a fluid layout

Attempting to align text elements within a responsive layout presents challenges due to the fluid nature of <div> sizes.

I recently discovered a fantastic method for horizontally and vertically centering a child <div> inside its parent <div>, which can be seen in action here: fiddle. (Originally shared in the second technique of this guide)

However, upon closer inspection of the fiddle, it's evident that the Large Text element isn't perfectly centered vertically within the parent <div class="block">; instead, the entire child <div class="centered"> is centered.

When attempting to split the two text elements into separate <div>s and center only the one containing the Large Text element, the alignment becomes disrupted as the second <div> with the small text is moved outside the parent <div class="block">

What adjustments can be made to the existing centering solution to ensure the Large Text element is perfectly aligned within the parent <div class="block">, while still accommodating the presence of the small text element positioned just below the Large Text?

Answer №1

vertican-align was brought into CSS to replace the valign HTML attribute for tables. It's important to note that using display:inline-block; will not create a table cell and won't be perfectly centered with vertical-align. A workaround is using display:table on the parent and display:table-cell on the child, unless you don't mind excluding < IE8.

Aside from the mentioned method, there isn't a straightforward way to center within a parent. However, if you know the element's height, you can apply an old image placement trick on divs as well.

<div>
    <p>Centered Text, Horizontally and Vertically</p>
</div>

Here's the CSS:

div {
    positon:relative;
    text-align:center;
    height:400px;
}

div p {
    position:relative;
    display:inline-block;
    height:30px;
    margin-top:-15px;
    top:50%;
    background-color:#cccccc;
}

Example in Fiddle

If the above method doesn't work for you, you can also absolutely position the <p>, but then you'll need to horizontally center it without relying on text-align:center on the parent or display:inline-block on the child.

Answer №2

If you're in need of a solution, I have created a demo for you to check out: http://example.com/demo

To achieve the desired effect, ensure that the large text (identified as '.title' in my demo) has a fixed height. Then utilize negative margin on the .box element to move it upwards, setting the value equal to the height of the .title.

The structure should look like this:

<div class="container">

    <div class="box">
        <h1 class="title">Title</h1>
        <p>Some text</p>
    </div>

</div>

CSS:

.container {
    display: inline-block;      
    text-align: center;
    }
    .container:before {
        content: '';
        height: 100%;
        display: inline-block;
        vertical-align: middle;
        margin-right: -4px;
        }

    .box {
        display: inline-block;
        vertical-align: middle;
        width: 400px;
        margin-top: 70px; /* Height of .title. This is equivalent to the line-height of .title */
        }
    .title {
        display: block;
        margin: 0;
        padding: 0;     

        line-height: 70px;/* Adjust based on your design requirements */ 
        }       

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

Tips for creating a responsive iframe without relying on aspect ratio assumptions

Is there a way to create a responsive iframe without relying on a fixed aspect ratio? The width and height of the content are unknown until rendering. Keep in mind, using Javascript is an option. For instance: <div id="iframe-container"> <i ...

Reacting to a situation where the tailwind grid has an issue: the responsive column span is visible in the HTML, but

I'm having an issue with a grid that is not behaving as expected. I have set up a jsfiddle to show the behavior I am looking for, which relies on the responsive code: col-span-3 md:col-span-2 for one of the items. The problem arises when I inspect th ...

The fixed div with the z-index at the top isn't functioning properly

I need a div that remains fixed at the top of my page and overlaps any other elements on the page, similar to the blue search bar on Facebook. Currently, when I scroll down, the table ends up above the div, but I want it to be below the div instead. Here i ...

Navigate through the options on the left menu by sliding your

I'm attempting to create a menu that slides in a submenu from the left on hover, but the issue is that with this code, all submenus open instead of just the one related to the hovered link. Here is my HTML code: <ul id="NavMenu"> ...

Identify and target a particular DIV based on the URL for customization

My webpage has a collection of frequently asked questions (FAQs) on a page called faq.html. Here is an example structure: <div id="faq1">...</div> <div id="faq2">...</div> I am looking to create a pulsating or highlighting effect ...

What is the best way to determine the position of an element with text content

Currently facing an issue with positioning in my project. Attached is a snapshot of my desired layout. I've tried creating a starburst effect and adding text using this code: jsfiddle link, but I'm struggling to position the elements correctly ...

Rectangles on canvas, each with identical dimensions, appear in varying sizes when positioned at different locations

In my canvas, I have created two rectangles using the rect element. Both rectangles are supposed to be 40 units wide and 20 units tall. The first rectangle starts at coordinates 0,0 for its top-left corner, while the second one begins at 60,40. Interesti ...

Malfunctioning Line in Apple Safari Causing ReactJS Issues

I am encountering an issue with my <div className={`${classes.center} ${classes.or}`}>OR</div>. It appears that this problem is specific to Apple Safari only. The alignment on the right side seems to be broken, although it works fine on Google ...

Tips for styling your Angular Material Card on mobile devices

Currently, I am very happy with my desktop layout which looks like this: https://i.stack.imgur.com/tG0pw.png However, when it comes to the mobile version of my site, here is what I have so far: https://i.stack.imgur.com/KD1hh.jpg While I do like the ho ...

Draggable slider not functioning properly with linear interpolation

Recently, I've been delving into the world of "linear interpolation" and its application in creating easing effects. However, while the easing functionality of the draggable slider seems to be operational, I'm encountering an issue. The slider re ...

Place the delete and edit buttons on the right side of the card

I am trying to align the edit and delete buttons with the image and premise name on the same line. Both buttons should be placed on the right side and have the same size as the card. Currently, the layout looks like this: https://i.sstatic.net/sNikU.png ...

Escape sequences do not seem to be functioning properly when using innerHTML

I am facing an issue where a string containing HTML escape characters (such as < and >) needs to be rendered inside a div using innerHTML. The intention is for the escaped characters to appear as text rather than as actual HTML, but they still render ...

Fade out a component in Material UI/React by setting a timeout in the parent's useEffect hook for when it unmounts

Incorporating a fade out transition into my child component, <Welcome />, using Material UI's Fade component is my current goal. This transition should be triggered by two specific conditions: The timeout set in the useEffect function expires. ...

Create a duplicate of a div element, including all of its nested elements and associated events, using

Attempting to duplicate a div containing input fields but the event listeners are not functioning. Despite performing a deep copy in the following manner - let rows = document.querySelectorAll('.row'); let dupNode = rows[0].cloneNode(true); sh ...

Tips for avoiding HTML injections in HTML tooltips

I'm attempting to create a tooltip using HTML, but I need to escape specific HTML elements within it. So far, my attempts have been unsuccessful. Take a look at the example I've provided: http://jsfiddle.net/wrsantos/q3o1e4ut/1/ In this example ...

Step-by-step guide on integrating node.js and MySQL to store data from an online form in a database

Currently, I am attempting to insert data into a MySQL database using node.js by clicking the submit button. However, an error message has appeared and despite understanding it somewhat, I am unsure of how to proceed. Any assistance would be greatly apprec ...

How can you dynamically disable the submit button on a form in Angular 7+ based on the form's current status?

Let's consider a scenario with a button in our code: <button type="button" class="menu-button" [disabled]="isInvalidForm()">Save</button isInvalidForm() { console.log('I am running!'); return this.nameValidator.errors || this.last ...

The art of uploading images with HTML and CSS

Looking for guidance on how to convert this image bubble so that users can upload their images during account creation. When the user hovers over the image bubble, it should display "Upload profile image" and prompt them to upload an image upon clicking. A ...

What is the Angular alternative to control.disable when working with a QueryList?

I have encountered a challenge in my Angular form where I need to disable certain fields. The issue arises from the fact that many of the HTML tags used are customized, making it difficult to simply use the disabled attribute. To address this, I have opted ...

Scrollbar width does not expand when hovered over

I am having trouble increasing the width of the scrollbar when hovering over it. However, I keep receiving an error in the console stating that 'scrollbar.addEventListener' is not a function. JAVASCRIPT setTimeout(function() { const scrollbar ...