前端案例:五彩导航
效果图如下所示:
上图中元素块为链接,当鼠标放置在元素上方时则变色
注意点:
(1)链接属于行内元素,但需要高度宽度,因此需要使用到模式转换,将行内元素转化为行内块元素
(2)链接中的文字需要剧中
(3)需要设置背景图片
(4)鼠标经过时背景图片样式改变,使用到链接伪类选择器
STEP 1 搭建结构
Input:
)
Output:
STEP 2 基本样式修改
需要将链接(行内元素)转化为行内块元素,从而设置高度与宽度,并且将文字在水平和垂直方向上居中。
盒子中内容居中显示知识点:
让盒子中的内容水平居中:text-align: center;
让盒子中的内容垂直居中:line-height: (盒子的高度); //让行间距等于盒子高度
Input:
)
Output:
STEP 3 添加背景图片
(不好意思哈,没有图片材料)
<style>
.nav .bg1 {
background: url(#1) no-repeat;
}
.nav .bg2 {
background: url(#2) no-repeat;
}
.nav .bg3 {
background: url(#3) no-repeat;
}
.nav .bg4 {
background: url(#4) no-repeat;
}
.nav .bg5 {
background: url(#5) no-repeat;
}
</style>
<div class="nav">
<a href="#" class="bg1">五彩导航</a>
<a href="#" class="bg2">五彩导航</a>
<a href="#" class="bg3">五彩导航</a>
<a href="#" class="bg4">五彩导航</a>
<a href="#" class="bg5">五彩导航</a>
</div>
注意:由于背景图片高度包括小三角符号,因此直接让文字行高等于盒子高度会导致“五彩导航”文字偏下。
于是应将行间距稍微缩小,使得文字内容处于长方形背景图片的中间。
STEP 4 背景变化效果
<style>
.nav .bg1 {
background: url(#1) no-repeat;
}
.nav bg1:hover {
background: url(#1change) no-repeat;
}
</style>
代码
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.nav a {
display: inline-block; /* 模式转化为行内块 */
width: 120px; /* 设置宽度 */
height: 58px; /* 设置高度 */
text-align: center; /* 文字内容水平居中显示 */
line-height: 48px; /* 由于小三角也占高度,缩小行间距使得文字内容稍微偏上 */
color: white;
}
.nav .bg1 {
background: url(#1) no-repeat;
}
.nav .bg1:hover {
background: url(#1change) no-repeat;
}
.nav .bg2 {
background: url(#2) no-repeat;
}
.nav .bg2:hover {
background: url(#2change) no-repeat;
}
.nav .bg3 {
background: url(#3) no-repeat;
}
.nav .bg3:hover {
background: url(#3change) no-repeat;
}
.nav .bg4 {
background: url(#4) no-repeat;
}
.nav .bg4:hover {
background: url(#4change) no-repeat;
}
.nav .bg5 {
background: url(#5) no-repeat;
}
.nav .bg5:hover {
background: url(#5change) no-repeat;
}
</style>
</head>
<body>
<div class="nav">
<a href="#" class="bg1">五彩导航</a>
<a href="#" class="bg2">五彩导航</a>
<a href="#" class="bg3">五彩导航</a>
<a href="#" class="bg4">五彩导航</a>
<a href="#" class="bg5">五彩导航</a>
</div>
</body>
</html>