How to Add Horizontal Space Between Multiple Buttons in HTML and CSS
In this tutorial, you will learn how to add horizontal space between multiple buttons in HTML and CSS. Using the button element, clickable buttons are created for websites. A form can be filed on a website by clicking the button element. For a good user interface and user experience when designing button elements for a website, you might wish to leave some horizontal space between them.
There are multiple ways to add horizontal space between buttons. But for the sake of simplicity, we will use the CSS margin-left
property. We are using CSS flexbox to guarantee the horizontal alignment of button elements.
In the following example, we have multiple buttons and we will add some horizontal space between them. Please have a look over the code example and the steps given below.
HTML
- In the HTML file, we have 3 elements (
h3
,div
, andbutton
). - The parent
div
element has a class name of.main-container
, which we will use in the CSS file to horizontally center align the child elements. - The
h3
is a heading tag with some text content. - We have multiple button elements and all the button elements have been wrapped with a
div
. - The second and third child
div
have the same class name of.horizontal-space
, which we will use in the CSS file to give some horizontal space between the buttons. - In the head element, we have added a stylesheet (
style.css
) using the link element.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Horizontal space between mutile buttons</title> <link rel="stylesheet" href="./style.css"> </head> <body> <h3>Horizontal space between multiple buttons</h3> <div class="main-contianer"> <div> <button type="submit">Submit</button> </div> <div class="horizontal-space"> <button type="reset">Reset</button> </div> <div class="horizontal-space"> <button>Read More</button> </div> </div> </body> </html>
CSS
- We are selecting the
h3
element and setting thetext-align
property value to center to center align theh3
element. - We are selecting the parent
div
using the class name of.main-container
and setting thedisplay
property value to flex andjustify-content
property value to center to horizontally center align the child elements. - We are selecting the
button
element and setting thewidth
property value to 100px. As a result, all the buttons will have the same width. - Lastly, we are selecting the second and third child
div
using the same class name of.horizontal-space
and setting themargin-left
property value to 20px. As a result, the buttons will have some horizontal space between them.
h3 { text-align: center; } .main-contianer { display: flex; justify-content: center; } button { width: 100px; } .horizontal-space { margin-left: 20px; }