我试图垂直对齐导航栏中的左右两个浮动元素。 (“折叠”的导航栏已经应用了clearfix hack)。导航栏的高度由左侧浮动标题(默认为h2,2em)确定。然而,正确的浮动元素,一个带有输入和按钮的表单,即使尝试使用变换方法来垂直居中时,也不会居中放置。 如果我取消注释变换垂直对齐方法,它只是进一步向上发送表单(而不是向下和居中)。垂直对齐 - 导航栏中的浮动元素
CodePen(https://codepen.io/yunti/pen/xdvpQK)
https://codepen.io/yunti/pen/xdvpQK
.header {
background-color: darkorange;
}
.header-title {
float: left;
padding-left: 10px;
color: white;
font-weight: 400;
}
.form-header {
float: right;
padding-right: 10px;
/*position: relative;*/
/*top: 50%;*/
/*transform: translateY(-50%);*/
}
.clearfix:after {
content: "";
clear: both;
display: table;
}
input,
button {
vertical-align: middle;
}
.form-control {
margin: 10px;
height: 34px;
width: 180px;
border-radius: 4px;
border: 1px solid #ccc;
font-size: 18px;
color: #555;
}
.form-control::placeholder {
color: grey;
}
.btn {
margin-left: 10px;
height: 34px;
padding-left: 12px;
padding-right: 12px;
line-height: 1.42857143;
white-space: nowrap;
border: 1px solid transparent;
border-radius: 4px;
background-color: forestgreen;
font-size: 14px;
font-weight: 400;
color: white;
cursor: pointer;
}
<div class="header clearfix">
<h1 class="header-title">Weather App</h1>
<div class="form-header">
<form class="form-group">
<input class="form-control" type="text" placeholder="St. George, Utah" />
<button class="btn">Get Weather</button>
</form>
</div>
</div>
Thansk为您的答案(我应该提到需要支持IE9所以不能做flexbox,但感谢其他答案)。任何想法为什么转化方法不起作用? (在其他SO答案中提到 – Yunti
https://developer.mozilla.org/en-US/docs/Web/CSS/position?v=control'对于相对定位的元素,顶部或底部属性指定与法线的垂直偏移位置,左侧或右侧属性指定水平偏移量。当您在顶部/左侧/右侧/底部使用'%'时,仅用于“固定”或“绝对”或“粘性”位置,因为%是相对于父亲的,相对定位的元素的%不会做任何事情,如果你用'50px'而不是'50%'代替 –
,但不是问题中的方法是'亲戚'的位置? 'fixed','absolute'或'sticky'? – Yunti