Css 为什么这不能正确对齐我的元素?
我希望我的布局是,让h1垂直对齐在顶部导航div的中心,我希望ul位于页面右侧顶部导航的底部。为什么我会得到意想不到的结果?可能是因为你的空间太大了吗Css 为什么这不能正确对齐我的元素?,css,layout,html,Css,Layout,Html,我希望我的布局是,让h1垂直对齐在顶部导航div的中心,我希望ul位于页面右侧顶部导航的底部。为什么我会得到意想不到的结果?可能是因为你的空间太大了吗 在“id=”之后 另外,不要使用右键填充:700px对于h1元件,只需将ul元件向右浮动。顶部导航h1中的向右填充:700px规则将ul元件推离位置 像这样的方法应该会奏效: html, body { height: 100%; width: 100%; padding: 0 0 0 0; margin: 0 0
在“id=”之后
另外,不要使用
右键填充:700px
对于h1元件,只需将ul
元件向右浮动。顶部导航h1中的向右填充:700px
规则将ul
元件推离位置
像这样的方法应该会奏效:
html,
body {
height: 100%;
width: 100%;
padding: 0 0 0 0;
margin: 0 0 0 0;
}
#top-nav{
background-color: Gray;
width: 100%;
height: 135px;
padding: 0 0 0 0;
margin: 0 0 0 0;
}
#top-nav h1{
float: left;
margin: inherit;
padding-right: 700px;
}
#top-nav ul{
float: left;
bottom: 0;
}
#top-nav li{
text-align: right;
display: inline;
padding-right: 5px;
}
对于位于顶部导航元素底部的导航,可以使用绝对属性,因此它始终固定在底部。 不要像前面的答案所说的那样,为H1使用一个左浮动。 对于垂直对齐的h1,您可以尝试不同的填充以获得所需内容(或者您可以使用display:table…)制作更复杂的脚手架) 但更简单的是:
html,
body {
height: 100%;
width: 100%;
padding: 0; /* You can just have one 0 instead of "0 0 0 0". */
margin: 0;
}
#top-nav {
background-color: Gray;
width: 100%;
height: 135px;
}
#top-nav h1 {
float: left;
line-height: 135px; /* Set to the height of #top-nav */
margin: 0;
}
#top-nav ul {
float: right;
}
#top-nav li {
text-align: right;
display: inline;
padding-right: 5px;
}
它能回答吗
编辑有几种方法可以实现你想要的。F.e.,用于垂直对齐<代码> H1 在代码<>顶部Nav/<代码>:
#top-nav h1{
padding-top:30px;
display:inline-block;
width:auto;
vertical-align:middle;
}
#top-nav ul{
position:absolute;
top:100px;
right:5px;
}
#top-nav h1 {
...
line-height: 135px;
margin: 0;
}
用于对齐顶部导航底部的ul
:
#top-nav h1{
padding-top:30px;
display:inline-block;
width:auto;
vertical-align:middle;
}
#top-nav ul{
position:absolute;
top:100px;
right:5px;
}
#top-nav h1 {
...
line-height: 135px;
margin: 0;
}
由于不正确地使用布局元素,您遇到了问题。元素用于无序列表,而不是包含链接的菜单。另外,使用float
是非常不鼓励的,因为它只用于使文本环绕图像,而不用于布局。浮动必须清除,并且不能在浏览器中正常工作
这里的诀窍是使用绝对定位,并确保该值相对于容器,因此必须将#top nav
div设置为具有位置:relative
,否则其子元素将相对于第一个定位的父元素进行定位,在这种情况下,父元素很可能是body元素
这对我来说很好:
HTML:
它在某种程度上回答了这个问题。为什么改变衬垫顶部会影响ul的位置?是的,你说得对,我错过了一些东西,对不起。我正在查看代码中的错误。好的,我显示h1内联块并输入一个宽度:auto,这样它就不会“推”nav元素。现在可以了吗?为什么要将line height属性设置为父元素的高度?这将垂直对齐
元素。
<html>
<head>
<title>Test</title>
</head>
<body>
<div id="top-nav">
<h1>Sitename</h1>
<span>
<a href="#">Feed</a>
<a href="#">Profile</a>
<a href="#">Settings</a>
</span>
</div>
</body>
</html>
body { margin: 0; padding: 0; overflow-x: hidden;}
div#top-nav span {
position: absolute;
bottom: 0px;
padding: 0;
margin: 0;
text-align: right;
width: 97%;
}
div#top-nav span a {
padding: 0 2px;
}
div#top-nav {
background-color: gray;
width: 100%;
height: 135px;
margin: 0px;
padding: 5px;
position: relative;
}
div#top-nav h1 {
position: relative;
top: 0px;
margin: 0;
padding: 0;
}