EN
CSS - center button content
3
points
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.