html - 在页面上垂直和水平居中 CSS 菜单

标签 html css

在我网站的第一页上,我只想让导航菜单在页面上垂直和水平居中。我尝试了很多不同的方法,这是我最接近的方法。

我不确定如何将链接 1 到 4 水平居中,而且我也不确定菜单是否真的在蓝色框中垂直居中。

(此外,这不是实际的配色方案。我添加了彩色背景以显示每个元素的边界。)

这是 HTML:

<body>
<div id="centered">
<ul>
    <li><h1><a href="link1.html">LINK1</a></h1></li>
    <li><h1><a href="link2.html">LINK2</a></h1></li>
    <li><h1><a href="link3.html">LINK3</a></h1></li>
    <li><h1><a href="link4.html">LINK4</a></h1></li>
</ul>     
</div>
</body>

还有 CSS:

html, body   { 
    background-color: black; 
    height: 100%; 
    margin: 0; 
    padding: 0;
        color: white; 
        text-align: center; }

a { 
    text-decoration: none; 
    color: #fff;
    }

h1 {
    font-size: 1.5em;
    color: #000;
    }

#centered { 
    border: solid black; 
    background-color: blue; 
    height: 20%; 
    width: 100%;
    position: absolute; 
    top: 40%; 
    }

#centered ul {
    list-style-type:none;
    margin:0;
    padding:0;
    } 

#centered li {
    float:left;
    display:inline;
    }

此处演示:http://jsfiddle.net/chassen2/n84ey/

最佳答案

首先不要在链接中使用标题,其次...这里有一个 FIDDLE

<div id="centered">
  <ul>
    <li><a href="link1.html">LINK 1</a></li>
    <li><a href="link2.html">LINK 2</a></li>
    <li><a href="link3.html">LINK 3</a></li>
    <li><a href="link4.html">LINK 4</a></li>
  </ul>     
</div>


#centered { 
  border: none; 
  background: blue; 
  height: 150px; 
  width: 100%;
  text-align: center;
  position: absolute; 
  top: 50%;
  margin-top: -75px;
}

#centered ul {
  list-style: none;
  margin-top: 58px;
  padding: 0;
} 

#centered li {
  display: inline-block;
  margin: 0 20px 0 20px;
}

#centered li a { 
  text-decoration: none; 
  font-family: Verdana;
  font-size: 24px;
  color: #fff;
  transition: color 0.2s linear;
}
#centered li a:hover {
  color: #888;
}

关于html - 在页面上垂直和水平居中 CSS 菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20313117/

相关文章:

javascript - 自定义 HTML 输入组件

javascript - 使用 javascript 更改 HTML,而不使用选择器

javascript - 粘性元素在滚动条的毛孔上表现不同

javascript - 设置 <td> 宽度所需的 HTML/Javascript 技巧

html - 如何水平和垂直对齐放置 3 个按钮

html - 为什么 CSS 部分 :only-child selector not work?

jquery - 如何使用 Jquery 循环每个表并在运行时写入状态?

javascript - 使用 Canvas 元素作为文本区域

html - GWT DockPanel 与 Chrome 的格式不正确

javascript - 将 ASP.NET 服务器脚本添加到 moSTLy-static .JS/.CSS 文件而不丢失 IntelliSense?