catandmouse
catandmouse

Reputation: 11819

How to align an input tag to the center without specifying the width?

I have these HTML and CSS:

#siteInfo input[type="button"] {
  background: none repeat scroll 0 0 #66A3D2;
  border-color: #FFFFFF #327CB5 #327CB5 #FFFFFF;
  border-radius: 10px 10px 10px 10px;
  border-style: solid;
  border-width: 1px;
  box-shadow: 1px 1px 3px #333333;
  color: #FFFFFF;
  cursor: pointer;
  font-weight: bold;
  padding: 5px;
  text-align: center;
  text-shadow: 1px 1px 1px #000000;
}
<div id="siteInfo">
  <p>Some paragraph.</p>
  <input type="button" value="Some Button">
</div>

I'd like the button to be aligned to the center; however, even with text-align: center in the CSS, is still on the left. I also don't want to specify the width since I'd like it to change with the length of the text. How do I do that?

I know the solution to this is simple but I can't find a proper way to do it. I would sometimes wrap it around a <p> tag that is center aligned but that's extra mark-up which I'd like to avoid.

Upvotes: 54

Views: 377387

Answers (9)

avr-girl
avr-girl

Reputation: 557

To center an input within a button:

<button class="btn btn-outline-dark d-inline-flex justify-content-center align-items-center">
        My Button
        <input type="date" style="height:1.2rem;font-size: 0.7rem;" onchange="myFunction();" />
</button>

Upvotes: 0

PyCodr
PyCodr

Reputation: 1

This worked for me:

<div align="center">
  <input type="button" value="Some Button">
</div>

Upvotes: 0

simon
simon

Reputation: 631

you can use this two simple line code :

    display: block;
    margin:auto;

Upvotes: 5

Ayan
Ayan

Reputation: 8906

You can use the following CSS for your input field:

.center-block {
  display: block;
  margin-right: auto;
  margin-left: auto;
}

Then,update your input field as following:

<input class="center-block" type="button" value="Some Button">

Upvotes: 25

Hadi
Hadi

Reputation: 17

you can put in a table cell and then align the cell content.

<table>
   <tr>
     <td align="center">
        <input type="button" value="Some Button">
     </td>
   </tr>
</table>

Upvotes: 0

sralse
sralse

Reputation: 5

You can also use the tag, this works in divs and everything else:

<center><form></form></center>

This link will help you with the tag:

Why is the <center> tag deprecated in HTML?

Upvotes: -8

sandeep
sandeep

Reputation: 92843

write this:

#siteInfo{text-align:center}
p, input{display:inline-block}

http://jsfiddle.net/XfSz6/

Upvotes: 13

Jared
Jared

Reputation: 12524

To have text-align:center work you need to add that style to the #siteInfo div or wrap the input in a paragraph and add text-align:center to the paragraph.

Upvotes: 0

dotancohen
dotancohen

Reputation: 31511

You need to put the text-align:center on the containing div, not on the input itself.

Upvotes: 102

Related Questions