本篇主要實現一個簡單的水平菜單。這個菜單能隨著瀏覽器窗口寬度的變化而改變排列方式:當寬度不足以容納所有菜單項時,會自動折行,從而達到自適應的效果。
代碼如下:
<html>
<head><title>自適應菜單</title><base target="_blank" /></head>
<body>
<style>
#menu {
font-family:Arial, Helvetica, sans-serif;
font-size:14px;
}
#menu a,#menu a:visited {
display:block;
float:left;
color:#000;
text-decoration:none;
padding:5px;
margin:5px;
border-top:8px solid #9ab;
border-bottom:8px solid #9ab;
white-space:nowrap;
}
#menu a:hover{
color:#F00;
border-bottom:solid 8px #000;
border-top:solid 8px #000;
}
</style>
<div id="menu">
<a href="https://hovertree.com/">Home</a>
<a href="https://hovertree.com/tiku/">Contact Us</a>
<a href="https://hovertree.com/texiao/">Web Dev</a>
<a href="https://run.hovertree.com/">Web Design</a>
<a href="https://hovertree.com/map/">Map</a>
<a href="https://tool.hovertree.com/">工具</a>
<a href="https://hovertree.com/h/bjaf/u9bobx8n.htm">原文</a>
</div>
</body>
</html>
關鍵在於將菜單項設為 float:left 並加上 white-space:nowrap,如此一來當一行放不下時,後面的項目便會自動換行,實現自適應的排版效果。
效果: