-1

I have a div which I'm using as a submit button for my form, but I cannot figure out how to center it. When the margins are set to auto, it ends up being just slightly right off the center of the page and of other divs with the same css style.

#submit {
 background-color: blue;
 height: 80px;
 width: 720px;
 margin: 0 auto;
 text-align: center;
}
<form name="algForm">
  <div id='submit' onclick="document.forms['algForm'].submit();"></div>
</form>

Thanks.

finn102
  • 45
  • 4
  • Why are you using a div that is styled to act as a form submit button - the correct html element would be either an input type="submit" or a button type="submit"- it is important to use the semantically correct element for the job and the correct element in a form is NOT the div element. – gavgrif Jan 18 '19 at 02:33

2 Answers2

3

I don't think using <div> as a button is a good idea. Consider using <button> instead.

But as for your answer, what you did does work. It's just the <div>'s width is too big to notice.

Here's the same code with only reducing the width to 200px.

Click "Run code snippet" to see it in action.

#submit {
 background-color: blue;
 height: 80px;
 width: 200px;
 margin: 0 auto;
 text-align: center;
}
 <form name="algForm">
   <div id='submit' onclick="document.forms['algForm'].submit();"></div>
   </form>
   
Meligy
  • 35,654
  • 11
  • 85
  • 109
  • 2
    If you are using a button within a form - then you don't need the onclick event - you can simply do and it will automatically submit the form that it is located within. – gavgrif Jan 18 '19 at 02:57
  • 1
    I ended up just using a button and styling it in css instead of using a div and it is now working perfectly. Thanks. – finn102 Jan 18 '19 at 03:35
0

I used display flex and centered items and content. This will also keep all form elements centered.

 form{
 display:flex;
 align-items:center;
 justify-content:center;
 }

#submit {
 background-color: blue;
 height: 80px;
 width: 720px;
 margin: 0 auto;
 text-align: center;
}
 <form name="algForm">
   <div id='submit' onclick="document.forms['algForm'].submit();"></div>
   </form>
   
Jonny
  • 1,319
  • 1
  • 14
  • 26