在div中水平居中输入

时间:2016-09-08 18:44:18

标签: html css twitter-bootstrap

我知道已经回答了100次,但现有的解决方案似乎都不适用于我。

我想在div中水平居中输入字段。为什么横向居中如此痛苦?!?!?父div可能会根据屏幕大小而改变大小,因此保证金百分比不起作用。

HTML

  <div class="select" id="avatar">
    <h4>Please enter your name.</h4>
    <!-- Object i want to center-->
    <div class="input-group">
      <input type="text" class="form-control text-center" id="playerName">
    </div>

    <h4>And Select Your Ship</h4>
    <img class="avatars" id="ship1" src="images/spaceship1.png">
    <img class="avatars" id="ship2" src="images/spaceship2.png">
    <img class="avatars" id="ship3" src="images/spaceship3.png">
    <img class="avatars" id="ship4" src="images/spaceship4.png">
    <button class="btn" id="submitPlayer">Submit</button>
  </div>

父母CSS

    .select {
        background-color: white;
        z-index: 200;
        padding: 0px 15px 0px 15px;
        text-align: center;
        font-family: 'Krona One', sans-serif;
        border: medium dashed green;
        margin-left: 25%;
        margin-right: 25%;
    }

我也想把这一个放在中心,我认为它将是相同的解决方案,但除了正文之外它没有父。

<div class="input-group">
  <input class="text-center" type="text" id="word">
</div>

2 个答案:

答案 0 :(得分:2)

为什么不使用Bootstrap的center-block类..

<div class="input-group center-block">
  <input class="center-block" type="text" id="word">
</div>

http://www.bootply.com/sTboTk5CvU

答案 1 :(得分:0)

输入和按钮就像img,你可以将它们显示为块并使用margin:auto;所以他们独自站在中间而不使用100%的宽度/空间:

.select {
  background-color: white;
  z-index: 200;
  padding: 0px 15px 0px 15px;
  text-align: center;
  font-family: 'Krona One', sans-serif;
  border: medium dashed green;
  margin-left: 25%;
  margin-right: 25%;
}
button.btn#submitPlayer {
  display: block;
  margin: auto;
  }
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="select" id="avatar">
  <h4>Please enter your name.</h4>
  <!-- Object i want to center-->
  <div class="input-group">
    <input type="text" class="form-control text-center" id="playerName">
  </div>

  <h4>And Select Your Ship</h4>
  <img class="avatars" id="ship1" src="images/spaceship1.png">
  <img class="avatars" id="ship2" src="images/spaceship2.png">
  <img class="avatars" id="ship3" src="images/spaceship3.png">
  <img class="avatars" id="ship4" src="images/spaceship4.png">
  <button class="btn" id="submitPlayer">Submit</button>
</div>

你可以对输入做同样的事情:

.input-group,
input#word.text-center{
  display: block;
  margin: auto;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="input-group">
  <input class="text-center" type="text" id="word">
</div>