Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
124
rated 0 times [  128] [ 4]  / answers: 1 / hits: 17404  / 9 Years ago, sun, october 18, 2015, 12:00:00

Let's say that I have a div in an html document with an absolute position, like so:



<div style=position:absolute>Hello!</div>


Now let's say I want to give it an X and a Y (likely through JQuery, for my purposes). This is easy enough, just set the left and top properties to X and Y respectively.

This task, however, gets a great deal harder when the X and Y are to be the center of this div. If the size of the div is not always guaranteed to be the same, you can't just offset the X and Y to the approprate amount.

If it is possible, how does one set the center of a div to a specific X and Y? In case it helps, these divs will only ever contain text, no sub elements.

I would prefer to use CSS rather than JavaScript, but if that is necessary, I'd be okay with it.


More From » jquery

 Answers
23

Two ways to center a div vertically and horizontally:



Method 1: Absolute Positioning



#box {
position: absolute;
left: 50%; /* relative to nearest positioned ancestor or body element */
top: 50%; /* relative to nearest positioned ancestor or body element */
transform: translate(-50%, -50%); /* relative to element's height & width */
}


DEMO: http://jsfiddle.net/19pu1g72/



Method 2: Flexbox



body {
display: flex; /* establish flex container */
justify-content: center; /* center flex items horizontally, in this case */
align-items: center; /* center flex items vertically, in this case */
}


DEMO: http://jsfiddle.net/19pu1g72/1/


[#64699] Thursday, October 15, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sabrina

Total Points: 92
Total Questions: 92
Total Answers: 85

Location: Palestine
Member since Thu, Feb 2, 2023
1 Year ago
;