Skip to main content

Posts

Showing posts from December, 2021

Two cool ways to center content in CSS

You may have seen this question, center a div, or whatever, in interviews or other places. I am sure there are other approaches than I am sharing here, but I found these two cool ideas from multiple places (see refs at the end). These are not my original ideas so I will be sure to share where I learned these from:   Using display:flex  Make sure you know how flex works, but to do centering with flex, it's ridiculously simple: div .container { display : flex ; justify-content : center ; /* horizontal alignment */ align-items : center ; /* vertical alignment */ flex-direction : column ; /* since we are doing a vertical column */ padding : 1rem 3rem ; /* not related to centering */ }  Now everything inside <div class="container"> </div> will be centered in both directions! Using display:grid  You are so going to thank for me this one, you are welcome. This one is so simple it does not even need an explanation does it?   div .container {

CSS: em vs rem font sizes

 When do you use em and when do you use rem? If you have ever asked this, you are like me :) So welcome. Basically, to save you time here it is: - If you want your font-size relative to the container's font-size, use em - If you want your font-size relative to the 'root' (or html) element's font-size, use rem! If you just stop reading now that might be sufficient, but if you are more curious, go on. Example companion codepen: https://codepen.io/binodpanta/pen/RwLWRra Basically your page should ideally always have a default font-size specified for the root, such as  :root { font-size: 1em; } This typically becomes 16px default for the base font size. Now, if you use rems in your elements' styles you get a consistent scaling wrt this number! so if you do div.someclass { font-size: 0.5rem; } you are going to always get a nice scaled font size regardless of screen size. So all your fonts will scale relatively throughout the app!  If you had used 0.5em, your calculated