如何在DIV中定位输入字段

时间:2014-12-27 02:32:29

标签: html css

我正在尝试将输入字段放在其父div中。我想把盒子向右浮动并垂直居中,但我似乎无法让它工作。

这是我的HTML:

<!DOCTYPE html>
<head>
    <link rel="stylesheet" type="text/css" href="index.css">
    <script src="index.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<html>
    <div id="millitary_conflict">Millitary Conflict<input type="number" value="0" "required"></div>
    <div id="treasury_contents">Treasury Content</div>
    <div id="wonder">Wonders</div>
    <div id="civillian_structures">Civillian Structures</div>
    <div id="commercial_structures">Commercial Structures</div>
    <div id="guilds">Guilds</div>
    <div id="scientific_structures">Scientific Structures</div>   
</html>

这是我的CSS:

div{
    height: 100px;
    width: 600px;
    margin-top: 10px;
    margin-left: auto;
    margin-right: auto;
    box-shadow: 2px 2px 5px gray;   
}

input{
    position: relative;
    display:block;
    float: right;
    margin-top: auto;
    padding: 0px;
}

#millitary_conflict{
    background-color: #FF6666;
}

#treasury_contents{
    background-color: #FFFFCC;
}

#wonder{
    background-color: #FFD633;
}

#civillian_structures{
    background-color: blue;
}

#commercial_structures{
    background-color: #FFFF66;
}

#guilds{
    background-color: purple;
}

#scientific_structures{
    background-color: green;
}

提前感谢您的帮助,我还在学习!

1 个答案:

答案 0 :(得分:0)

只需将top: 50%transform: translateY(-50%)添加到input

这将做的是:

  1. transform: translateY(-50%)会将input元素移到其顶部,即height的一半。

    enter image description here

  2. top: 50%input元素居中。

    enter image description here

  3. &#13;
    &#13;
    div {
      height: 100px;
      width: 600px;
      margin-top: 10px;
      margin-left: auto;
      margin-right: auto;
      box-shadow: 2px 2px 5px gray;
    }
    input {
      position: relative;
      display: block;
      float: right;
      margin: auto;
      padding: 0px;
      top: 50%;
      transform: translateY(-50%);
    }
    #millitary_conflict {
      background-color: #FF6666;
    }
    #treasury_contents {
      background-color: #FFFFCC;
    }
    #wonder {
      background-color: #FFD633;
    }
    #civillian_structures {
      background-color: blue;
    }
    #commercial_structures {
      background-color: #FFFF66;
    }
    #guilds {
      background-color: purple;
    }
    #scientific_structures {
      background-color: green;
    }
    &#13;
    <div id="millitary_conflict">Millitary Conflict
      <input type="number" value="0" "required">
    </div>
    <div id="treasury_contents">Treasury Content</div>
    <div id="wonder">Wonders</div>
    <div id="civillian_structures">Civillian Structures</div>
    <div id="commercial_structures">Commercial Structures</div>
    <div id="guilds">Guilds</div>
    <div id="scientific_structures">Scientific Structures</div>
    &#13;
    &#13;
    &#13;