Html 如何在不指定宽度的情况下将输入标签与中心对齐?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9264835/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 22:30:24  来源:igfitidea点击:

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

htmlcss

提问by catandmouse

I have these HTML and CSS:

我有这些 HTML 和 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: centerin 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?

我希望按钮与中心对齐;然而,即使text-align: center在CSS中,仍然在左边。我也不想指定宽度,因为我希望它随着文本的长度而改变。我怎么做?

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.

我知道解决这个问题的方法很简单,但我找不到合适的方法来做到这一点。我有时会将它包裹在一个<p>居中对齐的标签周围,但这是我想避免的额外标记。

回答by dotancohen

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

您需要将 放在text-align:center包含 div 上,而不是放在输入本身上。

回答by sandeep

write this:

写这个:

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

http://jsfiddle.net/XfSz6/

http://jsfiddle.net/XfSz6/

回答by Ayan

You can use the following CSS for your input field:

您可以为输入字段使用以下 CSS:

.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">

回答by Hadi

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>

回答by Jrod

To have text-align:centerwork you need to add that style to the #siteInfodiv or wrap the input in a paragraph and add text-align:centerto the paragraph.

为了text-align:center工作,您需要将该样式添加到#siteInfodiv 或将输入包装在一个段落中并添加text-align:center到该段落中。

回答by sralse

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

您还可以使用标签,这适用于 div 和其他所有内容:

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

This link will help you with the tag:

此链接将帮助您使用标签:

Why is the <center> tag deprecated in HTML?

为什么 HTML 中不推荐使用 <center> 标签?