【问题标题】:Vertical and horizontal alignment of input field in a divdiv中输入字段的垂直和水平对齐
【发布时间】:2014-09-18 21:23:49
【问题描述】:
任何人都可以帮助我解决这段愚蠢的代码,我花了将近 2 个小时试图弄清楚如何使它工作。目标是使输入字段在水平条内垂直和水平居中。
这是一个简化的代码:
HTML:
<div class="navigationBar">
<input type="text" id="searchField">
</div>
CSS:
.navigationBar{
width:100%;
height: 40px;
background-color: rgb(102,102,102);
}
#searchField{
margin; auto;
height: 25px;
width: 200px;
}
我也尝试过显示模式,改变位置类型但没有运气。
这里是code
【问题讨论】:
标签:
html
css
vertical-alignment
【解决方案1】:
添加行高会使其垂直居中。
.navigationBar{
width:100%;
height: 40px;
background-color: rgb(102,102,102);
}
#seachfield
margin; 0, auto;
height: 25px;
line-height: 40px;
width: 200px;
}
【解决方案2】:
答案很简单,去掉 #nav 元素的 padding 并将他的 height 和 line-height 设置为 40px 然后设置 display: inline-block for #search
#nav {
line-height: 40px;
height: 40px;
}
#search {
display: inline-block;
}
【解决方案3】:
试试下面的 CSS:
.navigationBar{
width:100%;
height: 40px;
background-color: rgb(102,102,102);
position:relative;
}
#searchField{
margin: auto;
height: 25px;
width: 200px;
position:absolute;
left:0px; right:0px; top:0px; bottom:0px;
}
PS:不是margin; auto;,正确的语法是margin: auto;
DEMO
【解决方案4】:
添加display:block;
#searchField{
display:block;
margin: 2px auto;
height: 25px;
width: 200px;
}
边距自动:顶部和左侧
添加'text-align: center;'=>(不仅是对齐文本)
.navigationBar{
width:100%;
height: 40px;
background-color: rgb(102,102,102);
text-align: center;
}
#searchField{
height: 25px;
width: 200px;
display:inline-block;
margin:4px auto;
}
【解决方案5】:
2 种方法
第二种方法实际上是使用最新的 css 功能所以,小心
1.)
.navigationBar { position: relative;}
#searchField { width: 300px;
height: 100px;
padding: 20px;
position: absolute;
top: 50%;
left: 50%;
margin: -70px 0 0 -170px;
}
2.)
.navigationBar { position: relative;}
#searchField { position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}