How to align a button to the right side using CSS?

In this tutorial, we will learn a few easy methods that we can use to align a button to the right side of its parent container.

The easiest way of doing this is to place the button inside a div element and then apply text-align: right; on this parent div element. The text-align property lets you easily align items to the right, center or left side of the parent container.

The following example aligns a button to the right side of its parent div element:

Example:

div{
   text-align: right;
}

Right align a button using CSS Float

The problem with the text-align: right; is that it aligns each of the child elements to the right side of the container even if we want only the specific element to be right-aligned.

We can easily overcome this problem with the CSS float property. The float property is only applied to the specific element that you want.

The following example will only float the button to the right side of its parent div without affecting other elements:

Example:

div > button{
   float: right;
}

Right align a button using CSS grids

If you don’t like either of the two methods, CSS grids is the best alternative for you. CSS grids lets you easily control the position of the grid items both horizontally as well as vertically.

To right align a button using CSS grids all you need to do is place the button(s) inside a div container and make this div a grid container by applying display: grid; on it.

Now, to right align the button(s) inside this grid container apply justify-content: right; on the same div element. It will automatically pull all the child elements to the right. The justify-content property lets you align items horizontally inside their container.

Here is a fully working example that aligns the button to the right:

Example:

div{
    display: grid;
    justify-content: right;
    border: 2px solid red;
    padding: 10px;
}

Note: To align a button vertically use align-items: center; on the grid container. The align-items property controls the vertical alignment of elements inside their parent container.

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts