好吧,我又开始做前端的工作了——这真的不是我的强项——但我被难住了。
我有一个带有 Logo 的 div,我需要将一些文本与其对齐,在 div 中垂直居中。每次我尝试使元素正确 float 时,它似乎都在 div 之外(不知何故?)。
相关的 HTML:
<div id="wrapper-header">
<div id="wrapper-nav-header">
<div id="header-logo">
<span id="header-logo-span"><a href="/"><img src="mylogo.png" /></a></span>
<span id="header-customer-name">Customer Name</span>
</div>
</div>
...
</div>
相关 CSS:
#wrapper-header {
background-color: #fff;
position: fixed;
z-index: 999;
width: 100%;
padding: 0;
white-space: nowrap;
font-size: 13px;
line-height: 1
}
#wrapper-header #header-logo {
margin-left: 20px;
padding: 10px 0;
}
#wrapper-header #header-logo img {
max-height: 40px;
vertical-align: middle;
}
#wrapper-header #header-customer-name {
vertical-align: middle;
}
我需要做什么才能让这个 header-customer-name 元素正确 float ?
最佳答案
你可以尝试使用 flex box:
html, body{
margin: 0;
padding: 0;
}
#wrapper-header {
background-color: #fff;
position: fixed;
z-index: 999;
width: 100%;
padding: 0;
white-space: nowrap;
font-size: 13px;
line-height: 1
}
#header-logo {
margin-left: 20px;
padding: 10px 0;
display: flex;
align-items: center;
}
#header-logo img {
max-height: 40px;
vertical-align: middle;
}
#header-customer-name {
flex-grow: 1;
text-align: right;
}
<div id="wrapper-header">
<div id="wrapper-nav-header">
<div id="header-logo">
<span id="header-logo-span"><a href="/"><img src=http://i.stack.imgur.com/gijdH.jpg?s=328&g=1" /></a></span>
<span id="header-customer-name">Customer Name</span>
</div>
</div>
</div>
或者您可以像这样为您的 header-customer-name
计算适当的填充:
html, body{
margin: 0;
padding: 0;
}
#wrapper-header {
background-color: #fff;
position: fixed;
z-index: 999;
width: 100%;
padding: 0;
white-space: nowrap;
font-size: 13px;
line-height: 1
}
#header-logo {
margin-left: 20px;
padding: 10px 0;
}
#header-logo img {
max-height: 40px;
vertical-align: middle;
}
#header-customer-name {
float: right;
padding: 12px 0; /*you can change for a more precise value*/
}
<div id="wrapper-header">
<div id="wrapper-nav-header">
<div id="header-logo">
<span id="header-logo-span"><a href="/"><img src=http://i.stack.imgur.com/gijdH.jpg?s=328&g=1" /></a></span>
<span id="header-customer-name">Customer Name</span>
</div>
</div>
</div>
无论如何,如果您指的是 header-customer-name
在 #wrapper-header
的右侧出现,那可能是因为它有 position: fixed
和 width: 100%
,这就是我添加样式的原因:
html, body{
margin: 0;
padding: 0;
}
在这里查看我的答案以更好地理解 White Space Appears Right of Browser Window When at Full Screen
这与问题无关,但可以帮助你
不要高估
一般来说,不要提供不必要的信息。
// bad
ul#someid {..}
.menu#otherid{..}
#id1 #id2{...}
// good
#someid {..}
#otherid {..}
#id2{...}
关于html - div 右侧的 float 元素出现在外部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31957031/