Wednesday, February 3, 2021

Handy CSS Tricks: Centering Things in the Middle of the Page

 Many sites have everything on it centered directly on the middle of the page, but doing this can be a little tricky at first. Text can easily be centered by just one line with:

text-align:CENTER;

 but centering elements can be a little trickier. The way I am going to show here will work on any size monitor, uses basic CSS rules, so it's easy, and only takes three lines to write. First, add a class or an id to the element that you want to center. 

<img id="center-element">

Now select it in your <style> tag like this:

<style> #center-element {  } </style>

Now declare the width of the element and set it to 50% (Or any percent value) value. This will make it so that the element's width is 50% of the available space on the page. The height will automatically adjust unless you have set the height. 

<style> #center-element { width:50%;  } </style>

Now that the element takes up 50% of the page, we need to declare the margin-left and margin-right properties. Think about the amount of space left up (In our case 50% is still left). If we want it to be in the middle, we need the space on the left and right half of what remains (25% in our example). 

<style> #center-element {width:50%; margin-left:25%; margin-right:25%;} </style>

Now all 100% of the space is used up, and your element should be in the middle of the page!

 

 

 

No comments:

Post a Comment