如何在标题div中将两个div水平居中? [英] How to horizontally center two divs within a header div?
问题描述
我有一个标头div,它固定在浏览器窗口的顶部,宽度为100%。标头div中有一个带标题文本的div,还有一个有水平列表的div。水平列表div应该出现在标题文本div的右侧。
I have a header div that is fixed to the top of the browser window at 100% width. Within the header div there is a div with title text and there is a div with a horizontal list. The horizontal list div should appear to the right of the title text div.
这是我的CSS和HTML:
Here is my CSS and HTML:
#header {
position:fixed;
top:0;
left:0;
right:0;
background-color:#333333;
padding:20px;
}
#title {
float:left;
color:#000000;
font-size:30px;
margin-right:24px;
background-color:#ffffff;
padding:8px;
}
#navigation ul {
padding:0;
margin:0;
list-style-type:none;
}
#navigation ul li {
display:inline;
margin-right:20px;
padding:3px;
background-color:#ffffff;
}
#navigation ul li a {
color:#000000;
text-decoration:none;
}
<div id="header">
<div id="title">Some Title Text</div>
<div id="navigation"><ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul></div>
</div>
现在,标题和导航div在标题div中保持对齐。我该如何水平居中标题和导航div?
So right now the title and navigation divs are left aligned inside the header div. How can I horizontally center the title and navigation divs?
编辑:希望使用不使用硬编码宽度的解决方案(例如。 宽度:500px
),因为列表大小并不总是相同。
Would prefer a solution that doesn't use a hardcoded width(eg. width: 500px
) since the list size isn't always the same.
推荐答案
一种用于更改标题和/或两个div宽度的方法(如果标题变长或变短,或者添加或删除了导航项):
A method that works with changing widths of the header and/ or of the two divs (if the title gets longer or shorter or if navigation items are added or removed):
在 #header
上设置 text-align:center
,并在 display:inline
-演示 http://dabblet.com/gist/3151355 #title
和 #navigation
上的-block
Set text-align: center
on the #header
, and display: inline-block
on #title
and #navigation
- demo http://dabblet.com/gist/3151355
CSS中的更改:
#header {
position:fixed;
top:0;
left:0;
right:0;
background-color:#333333;
padding:20px;
text-align: center; /* added */
}
#title {
color:#000000;
font-size:30px;
margin-right:24px;
display: inline-block; /* took out float:left and added this */
background-color:#ffffff;
padding:8px;
}
#navigation {
display: inline-block; /* added */
}
我还添加了 #navigation ul li:last-child {margin-right:0}
,以使最后一个列表项后没有 24px
的边距(使其在导航的右侧看起来有更多空间)
I've also added #navigation ul li:last-child {margin-right:0}
in order not to have 24px
margin after the last list item (which would make it seem like there is more space on the right side of the navigation)
这篇关于如何在标题div中将两个div水平居中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!