-1

I'm trying to center a pair of buttons within a form. These buttons are wrapped in <div> which has display: inline-block set against it so the <div> is only as wide as the buttons. The parent to the <div> which is a <form> element has fixed-width: 290px set against it.

However, on the <div>, when I set margin-left: auto; margin-right: auto, the <div> doesn't center itself within the <form>. I have even set display: block against the <form> element too to no avail.

What am I doing wrong?

HTML:

<form id="schemeForm">
    <!--Other HTML elements-->
    <div id="formButtons">
        <input type="button" value="Back" />
        <input type="submit" value="Submit" />
    </div>
</form>

CSS:

#schemeForm {
    width: 290px;
    display: block;
}

#formButtons {
    display: inline-block; /*to make it only as wide as buttons*/
    margin-left: auto;
    margin-right: auto;
}

Example Code Snippet:

#schemeForm {
    width: 290px;
    display: block;
    background-color: black;
}

#formButtons {
    display: inline-block; /*to make it only as wide as buttons*/
    margin-left: auto;
    margin-right: auto;
    background-color: orange;
}
<html>
<body>
<form id="schemeForm">
    <!--Other HTML elements-->
    <div id="formButtons">
        <input type="button" value="Back" />
        <input type="submit" value="Submit" />
    </div>
</form>
</body>
</html>
RoyalSwish
  • 1,503
  • 10
  • 31
  • 57
  • 1
    _“What am I doing wrong?”_ - you are assuming auto margins would work on inline-block elements, which they simply do not. – CBroe Jun 29 '20 at 12:59
  • @CBroe ahh forgive me, but I thought the purpose of inline-block was to preserve the properties of block elements? If that isn't the case then I have to assigned fixed values to the buttons before assigning a fixed width to the div then. – RoyalSwish Jun 29 '20 at 13:05

3 Answers3

1

You may want to give text-align: center to #schemeForm

<html>
    <style>
        #schemeForm {
        width: 290px;
        display: block;
        background-color: black;
        text-align: center;
}

#formButtons {
        display: inline-block; /*to make it only as wide as buttons*/
        background-color: orange;
}
    </style>
<body>
    <form id="schemeForm">
        <div id="formButtons">
            <input type="button" value="Back" />
            <input type="submit" value="Submit" />
        </div>
    </form>
</body>
</html>
Mehmet Ali
  • 313
  • 3
  • 15
0

Keep #formButtons display: block and set text-align: center.

#schemeForm {
  width: 290px;
  display: block;
}

#formButtons {
  display: block;
  text-align: center;
}
<html>
<body>
<form id="schemeForm">
    <!--Other HTML elements-->
    <div id="formButtons">
        <input type="button" value="Back" />
        <input type="submit" value="Submit" />
    </div>
</form>
</body>
</html>
-1

It looks like you want display:block; instead of display:inline-block;