Languages
[Edit]
EN

CSS - center button content

3 points
Created by:
Root-ssh
68230

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>
<html>
<body>
  <style>

    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 */
    }

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

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

Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join