5 Tips of Defining Vertical Centering With CSS Tags:

No comments
5 Tips of Defining Vertical Centering With CSS Tags:

There are a multiple ways to defining vertical centering objects with CSS, but it can be difficult to select the easiest one. I’m going to share you all the best ways I’ve seen.

Vertical centering with CSS is not a every's cup of tea. There are many different ways that may not compatible with some browsers. Let’s review 5 different ways to vertically centering objects:

Method 1
 
This method sets some
s to display like a table, so we can use the table’s vertical-align property (which works very differently for other elements).



Content goes here



#wrapper {display:table;}
#cell {display:table-cell; vertical-align:middle;}


Method 2

This method will use an absolutely positioned div, which has the top set to 50% and the top margin set to negative half the height of the content. This means the object must have a fixed height, that is defined by CSS.

Because it has a fixed height, you may want to set overflow:auto; to the content div, so if there is too much content to fit in, a scrollbar will appear, instead of the content continuing on outside the div!


Content Here


#content {position:absolute; top:50%; height:240px; margin-top:-120px; /* negative half of the height */}


Method 3

In this method, we will insert a div above the content element. This will be set to height:50%; and margin-bottom:-contentheight;. The content will then clear the float and end up in the middle.




Content here


#floater {float:left; height:50%; margin-bottom:-120px;}
#content {clear:both; height:240px; position:relative;}


Method 4

This method uses a position:absolute; div with a fixed width and height. The div is then told to stretch to top:0; bottom:0;. It can’t because of the fixed height, so margin:auto; will make it sit in the middle. This is similar to using the very common margin:0 auto; to horizontally centre block elements.



Content here


#content {position:absolute; top:0; bottom:0; left:0; right:0;
margin:auto; height:240px; width:70%;}


Method 5

This method will only centre a single line of text. Simply set the line-height to the height of the object, and the text sits in the middle



Content here


#content {height:100px; line-height:100px;}

No comments :

Post a Comment