using element’s own (not parent’s) width for calculation or percentage in css, without javascript

One pure CSS solution is to use transform.

element
{
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}

Notes:

  1. You can use top: 50%; for vertical and left: 50%; for horizontal.
  2. You would then use translateY(-50%) for vertical and translateX(-50%) for horizontal centering.
  3. You can also use this trick to align elements to the bottom or right of it’s parent, like in a table-cell by using 100% instead of 50% in the css.
  4. If you want to support older browsers, then you’ll need to use prefixes for transform. I highly recommend autoprefixer in your workflow.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)