Centering things including Div Horizontally and Vertically

a big amount of css styling effort comes down to aligning and centering (as well as measuring, setting heights etc.)
there are lots of options so its important to choose the right solution for the problem at hand
here's my list of useful solutions

1. simple horizontal centering for text or control: "text-align: center"
  • for paragraph or heading text or button see here using  "text-align: center". 
    • You can also use "text-align: center" to center things within a div, such as a button e.g. 
      • <div style="text-align: center"><button type="submit" class="btn btn-large btn-embossed btn-info">Do it</button></div>
    • bootstrap has a "text-centered" css class which is defined as: "text-align: center"
  • for a block including text or image see here (you must set width)
2. vertical centering; quite trickier
  • this is a handy technique from css tricks where you know the size of the control to be centered vertically as well as well as if you don't know size of child. I have used this.
  • another option is to use display: table-cell see here (good detailed explanation here), but it uses css display: table-cell which I kinda don't like
  • I've found the best center both vertically and horizontally to be the following: this little gem does horizontal and vertical both..but you do have to set width and height (see css below for posterity). I have used this.

this is also a good article with detailed explanations of centering things (mucho appreciated)...but the vertical solution is not as elegant as the little gem", which incidentally is listed in a js fiddle as reply to the post...so who's the author eh!



center both horiz and vert css
div {
    width: 100px;
    height: 100px;
    background-color: red;

    position: absolute;
    top:0;
    bottom: 0;
    left: 0;
    right: 0;

    margin: auto;
}

Comments

Popular posts from this blog

deep dive into Material UI TextField built by mui

angular js protractor e2e cheatsheet

react-router v6.4+ loaders, actions, forms and more