CSS - center button content

3 points
Created by:

In this short article we would like to show how to center button content using CSS with absolute positioning.

Let's get some assumptions:

  • buton has fixed size, e.g. 30x30 px,
  • inside button we can put text or something different.

Simple example:

// ONLINE-RUNNER:browser;

<!doctype html>

    a.button {
        position: relative;  /* <------------------- required */
        background: silver;
        width: 160px;  /* <------------------------- required */
        height: 60px;  /* <------------------------- required */
		display: block;  /* <----------------------- required */
      	cursor: pointer;
    span.content {
        position: absolute;  /* <-------------------- required */
        left: 50%;  /* <----------------------------- required */
        top: 50%;  /* <------------------------------ required */
        font-size: 14px;
        transform: translate(-50%, -50%);  /* <------ required */

  <a class="button" href="javascript: console.log('Button clicked!')">
    <span class="content">Click me!</span>

Note: check different ways how to center elements in this article.

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.