如何在标题div中将两个div水平居中?

编程入门 行业动态 更新时间:2024-10-28 13:24:46
本文介绍了如何在标题div中将两个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 #title 和 #navigation 上的-block -演示 dabblet/gist/3151355

Set text-align: center on the #header, and display: inline-block on #title and #navigation - demo dabblet/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水平居中?

本文发布于:2023-10-07 22:22:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1470682.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中将   水平   两个   标题   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!