制作:与其元素大小相同

时间:2015-01-05 20:11:17

标签: html css

我有一个导航菜单,每个项目都有不同大小的单元格。在每个项目下,我想要一个三角形图像来指示活动菜单项。 如何使:after反映出与父级相同的大小,以便我可以正确居中:after的内容?

菜单代码:

<div class="nav-collapse collapse">
    <ul class="nav nav-pills">
        <li><a href="#clients">Clients</a></li>
        <li><a href="#solutions">Solutions</a></li>
        <li><a href="#services">Services</a></li>
        <li><a href="#business">Your Business</a></li>              
        <li><a href="#security">Security</a></li>
        <li><a href="#partners">Partners</a></li>
        <li><a href="#Contact">Contact</a></li>
    </ul>
</div>      

2 个答案:

答案 0 :(得分:2)

此处的方法是在absolute元素上使用:after位置,并使用lia标记父级作为亲戚。像这样:

.nav > li a {
  position: relative;
}
.nav > li a:after {
  content: "\25B2";
  position: absolute;
  left: 50%;
  transform: translate(-50%, -100%);
}

检查代码段

&#13;
&#13;
* {
  margin: 0;
  padding: 0
}
.nav > li {
  height: 70px;
  line-height: 70px;
  background: orange;
  list-style: none;
  margin: 1px;
  float: left;
}
.nav > li a {
  position: relative;
  padding: 0 15px;
  display: block;
  color: white;
  font-family: 'verdana';
  text-decoration: none;
  transition: background .3s ease
}
.nav > li a:hover {
  background: red;
}
.nav > li a:after {
  content: "\25B2";
  position: absolute;
  color: white;
  top: 100%;
  line-height: normal;
  left: 50%;
  transform: translate(-50%, -100%);
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="nav-collapse collapse">
  <ul class="nav nav-pills">
    <li><a href="#clients">Clients</a>
    </li>
    <li><a href="#solutions">Solutions</a>
    </li>
    <li><a href="#services">Services</a>
    </li>
    <li><a href="#business">Your Business</a>
    </li>
    <li><a href="#security">Security</a>
    </li>
    <li><a href="#partners">Partners</a>
    </li>
    <li><a href="#Contact">Contact</a>
    </li>
  </ul>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

尝试此css,在内容中包含文字:“”并通过rgba将颜色设置为透明。然后将背景设置为图像

.nav-pills {
width: 100%;
display:block;
list-style:none;
}
.nav-pills li{
display:inline;
float:left;
margin: 0 20px;
padding:4px 10px
background:#d7d7d7;
text-align:center;
}
.nav-pills li::after { 
content: " Image";
padding: 4px 10px;
background:url(images/image.png);
background-color:orange;
color: rgba(255,255,255,0);
display:block;
}

查看我的codepen here