How to Give Horizontal Space Between Two Buttons in HTML and CSS
In this tutorial, you will learn how to give horizontal space between two buttons in HTML and CSS. A website’s clickable buttons are made using the button element. Through the use of the button element on a website, a form may be submitted. When developing button elements for a website, you may want to leave some horizontal space between them for a decent user interface and user experience.
There are multiple ways to give horizontal space between two buttons. But for the sake of simplicity, we will use the margin-left
property. To ensure that both the button elements are horizontally aligned, we are utilizing CSS flexbox.
In the following example, we have two buttons and we will give 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 two button elements and all the button elements have been wrapped with a
div
. - The last child
div
has a class name of.horizontal-space
, which we will use in the CSS file to give some horizontal gaps 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 two buttons</title> <link rel="stylesheet" href="./style.css"> </head> <body> <h3>Horizontal space between two buttons</h3> <div class="main-contianer"> <div> <button type="submit">Submit</button> </div> <div class="horizontal-space"> <button type="reset">Reset</button> </div> </div> </body> </html>
CSS
- We are selecting the
h3
element and setting thetext-align
property value to center to horizontally 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 the
width
property value to 100px. As a result, all the buttons will have the same width. - Lastly, we are selecting the second child
div
using the class name of.horizontal-space
and setting themargin-left
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; }