Ways to vertically center an absolutely positioned element

In the code snippet below, there is a .square-container that is absolutely positioned and contains a square. The goal is to vertically center the .square-container within its parent div.

.container {
    position: relative;
    background-color: blue;
}
.square-container {
    position: absolute;
    top: 0;
    right: 0;
    height: 30px;
    width: 30px;
}
.square {
    width: 100%;
    height: 100%;
    background-color: red;
}
.hello {
    padding: 15px;
}
<div class='container'>
    <p class='hello'>Hello</p>
    <div class="square-container">
        <div class='square'></div>
    </div>
</div>

Answer №1

To center absolute positioned elements vertically, apply top: 50%

Follow it with transform: translateY(-50%); for perfect alignment

.container {
        position: relative;
        background-color: blue;
    }
    .square-container {
        position: absolute;
        right: 10px;
        top: 50%;
        height: 30px;
        width: 30px;
        transform: translateY(-50%);
       
    }
    .square {
        width: 100%;
        height: 100%;
        background-color: red;
    }
    .hello {
        padding: 15px;
    }
<div class='container'>
    <p class='hello'>Hello</p>
    <div class="square-container">
        <div class='square'></div>
    </div>
</div>

Answer №2

.wrapper{
justify-content:center;
align-items:baseline;
}

Answer №3

A different approach is needed in this situation. By setting the container as a flex wrapper, absolute positioning becomes unnecessary and the additional square-container div wrapping the div.square can be eliminated.

To align the square to the right, there are two potential solutions:

A) Utilize auto-margins within the flex layout. By adding margin-left: auto to the div.square, it instructs the browser to position it as far away as possible from its left siblings.

B) Apply justify-content: space-between to the container. This directive prompts the flex container to evenly distribute the elements towards the sides.

While these methods offer minor variations, they may not have a significant impact in this scenario unless more elements are introduced.

Here is an updated example:

A

.container {
    display: flex;
    align-items: center;
    background-color: skyblue;
    padding: 15px;
}
.square {
    height: 30px;
    width: 30px;
    margin-left: auto;
    background-color: tomato;
}
<div class='container'>
    <p class='hello'>Hello</p>
    <div class='square'></div>
</div>

B

.container {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: skyblue;
    padding: 15px;
}
.square {
    height: 30px;
    width: 30px;
    background-color: tomato;
}
<div class='container'>
    <p class='hello'>Hello</p>
    <div class='square'></div>
</div>

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

The session name has not been properly defined

Sorry for any errors in translation. I'm facing an issue where the session name I insert is coming up as undefined. However, when I manually enter the username, everything works fine. View Image <? php session_start (); echo var_dump ($ _SESSION ...

The content displayed in the PrimeNG p-table is limited to only the table name with no additional information

After upgrading Angular to version 9, I switched from p-dataTable to p-table in PrimeNG. With a table named users, I intended to display them on the screen upon rendering the view using the following HTML: users = ['one','two','thr ...

Toggle child checkboxes when parent checkbox is clicked in angularjs

Can anyone help me figure out how to automatically select child checkboxes when the parent checkbox is clicked? In the code below, I have a parent checkbox in the table header and child checkboxes in the table body. When the parent checkbox is selected, ...

The function you are trying to use is not a valid jQuery function

Although I've come across this issue in previous posts, none of the solutions worked for me and it's really frustrating. I'm a newbie to javascript and I'm sure the answer is probably simple. I'm attempting to incorporate the rapt ...

Send Selected Input From Radio Button To Form Using a Function

Within the main php page titled tipComp.php, there is a script designed to submit a selected value from a radio button within a form: <script> $('input[type=radio]').on('change', function() { $(this).closest("form& ...

Tips for preserving dynamically generated HTML through Javascript during page reload

I have a straightforward question, but I haven't been able to find a suitable answer. Here's my situation: On my HTML page, I have a form. Using jQuery and AJAX, I submit the form and then use some JavaScript code to change the content of a spec ...

What's up with portable devices requiring two taps to hover over one DIV and affect another DIV?

Upon implementing "hover one DIV - affecting another inner DIV," a strange issue arose on iPad/iPhones where it now requires two taps to click on the link within the DIV with the hover effect: Below is the HTML code: <div class="portfblock"> &l ...

Expanding the size of a buffer array dynamically in JavaScript while adding items

Within the source table are several records stored. Upon clicking each record in the source table, the AddSelectedItem(sValue) function is triggered, adding those specific records to the destination table. The desired outcome is for the array to dynamica ...

Obtaining JSON data using Jquery results in the output of "undefined"

I am struggling to extract the correct values from a JSON document in order to display schedules in list view. Currently, when accessing the JSON document, I keep receiving "undefined" as the result. Below is an example of the JSON document: { "Ferries": ...

Issue with jQuery in Internet Explorer causing difficulties loading images

I'm experiencing an issue with my website where all the images load on top of each other when the site is first loaded, creating a chaotic mess. The desired functionality is for the images to remain invisible until specific words are clicked, which is ...

Determining the exact pixel height of a table row

Is there a way to use JavaScript to accurately determine the height of a table row in pixels? Specifically, I am looking for the measurement from the top of one green border to the top of the next green border. I have tried using jQuery's .height(), ...

Fixed-positioned left column in a styled table

Struggling to implement the solution provided in this popular topic on Stack Overflow about creating an HTML table with a fixed left column and scrollable body. The issue arises from my use of the thead and tbody tags, which are not addressed in the exampl ...

Missing information in input field using JQUERY

I've been attempting to extract a value from an input tag, but all I keep getting is an empty string. Upon inspecting the frame source, it appears as follows: <input type="hidden" name="" class="code_item" value="00-00000159" /> In order to re ...

What steps are involved in generating a scene dynamically with A-Frame?

Looking to transition from declarative coding in js and html to a programmatic approach with Aframe? You might be wondering if it's possible to modify your scene dynamically, here is an example of what you're trying to achieve: <!DOCTYPE html ...

Tips for implementing z-index property on table border

I am encountering an issue with an html file that contains a table. The table has one row element with the css property of position: sticky, while the other rows are just example rows with "some text" in each cell. Within column 5 of the regular rows, I h ...

Google Map with rounded corners that have a transparent design

Trying to create a circular Google map using CSS3 border-radius, but having issues with browsers other than Firefox. Here's the code snippet: <div class="map mapCircle" style="position: relative; background-color: transparent; overflow: hidden;"&g ...

Scraping using Regex to extract form_ids with varying values but identical names

Is there a way to extract the value of a form id from an HTML page using either regex or xpath, specifically focusing on scraping the value from the second instance of the form_id name? Any suggestions on the most effective method to accomplish this using ...

An illustration of the fundamental concepts of require.js

main.md <markdown> <head> <script data-main="script" src="http://requirejs.org/docs/release/2.1.8/minified/require.js"></script> </head> <body></body> </markdown> script.css defi ...

Every time I rotate my div, its position changes and it never goes back to

Trying to create an eye test by rotating the letter "E" when a directional button is clicked. However, facing an issue where the "E" changes position after the initial click instead of staying in place. Here is a GIF showcasing the problem: https://i.stac ...

Can one retrieve the CSS/XPath from a Capybara Element?

Is it possible to extract CSS/XPath from a Capybara Element? I have attempted to use #path but it doesn't appear to be effective. Here is the link I tried: The test is being executed on Selenium Webdriver. ...