I am confused about how can I force my div
element to be center (vertically
and horizontally
) at my page (mean which way or ways for cross browser compatibility)?
To center both vertically and horizontally, use padding and text-align: center : I am vertically and horizontally centered.
Just add margin: auto and a fixed width to the element you want to center, and the margins will force the element to center.
Set the display property of the span tag to inline-block to wrap multiple lines of text together. Give line-height to 20px to the span to give a gap between multiple lines of text. Keep the vertical-align to middle to vertically place the text exactly in the middle.
To center something in CSS, make sure the parent element has position: relative , and the element you want to center position: absolute and left: 50% and margin-left: -width/2 . That's the basic idea to center elements horizontally.
There are many methods :
CSS
<div style="width:200px;height:100px;position:absolute;left:50%;top:50%; margin-left:-100px;margin-top:-50px;"> <!–content–> </div>
2 . Center horizontally and vertically a single line of text
CSS
<div style="width:400px;height:200px;text-align:center;line-height:200px;"> <!–content–> </div>
3 . Center horizontal and vertical align of an element with no specific measure
CSS
<div style="display:table;height:300px;text-align:center;"> <div style="display:table-cell;vertical-align:middle;"> <!–content–> </div> </div>
This blog post describes two methods of centering a div both horizontally and vertically. One uses only CSS and will work with divs that have a fixed size; the other uses jQuery and will work divs for which you do not know the size in advance.
I've duplicated the CSS and jQuery examples from the blog post's demo here:
CSS
Assuming you have a div with a class of .classname, the css below should work.
The left:50%; top:50%;
sets the top left corner of the div to the center of the screen; the margin:-75px 0 0 -135px;
moves it to the left and up by half of the width and height of the fixed-size div respectively.
.className{ width:270px; height:150px; position:absolute; left:50%; top:50%; margin:-75px 0 0 -135px; }
jQuery
$(document).ready(function(){ $(window).resize(function(){ $('.className').css({ position:'absolute', left: ($(window).width() - $('.className').outerWidth())/2, top: ($(window).height() - $('.className').outerHeight())/2 }); }); // To initially run the function: $(window).resize(); });
Here's a demo of the techniques in practice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With