首页 > 解决方案 > 如何添加边框css

问题描述

HTML:

<ul>
   <li><a href="">someloooooooooooooooooooooong text </a></li>
   <li><a href="">someloooooooooooooooooooooong text </a></li>
</ul>

我怎样才能添加这样的边框?

在此处输入图像描述

我的CSS:

ul {

     display: block;
     width: 255px;
     border: 1px solid #007ab6;
}
 ul a {
     width: 225px;
     white-space: nowrap;
     text-overflow: ellipsis;
     overflow: hidden;
}
 ul a:hover {
     overflow: visible;
     width: unset;
     display: inline-block;
     border: 1px solid;
     background: #ebf7fd;
}

这就是它的外观,但这并不是我想要的。 在此处输入图像描述

标签: htmlcss

解决方案


我使用伪元素在悬停时添加边框和背景颜色。您也可以根据需要添加任意数量的列表。无需单独处理每个列表。

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

ul {
  display: block;
  width: 255px;
  border: 1px solid #007ab6;
  list-style: none;
  background: #fff;
  margin: 10px;
}

ul li {
  white-space: nowrap;
  overflow: hidden;
  width: 100%;
  text-overflow: ellipsis;
  display: inline-block;
  position: relative;
  vertical-align: middle;
}

ul li:before {
  content: '';
  position: absolute;
  top: -1px;
  left: -1px;
  right: -1px;
  bottom: -1px;
  background: #ffffff;
  border: 1px solid;
  z-index: -3;
  box-sizing: border-box;
}

ul li:after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  z-index: -2;
}

ul li:hover {
  overflow: visible;
  width: auto;
}

ul li a {
  position: relative;
  z-index: 1;
  text-decoration: none;
  background: #fff;
  padding: 10px;
  display: inline-block;
}
<ul>
  <li><a href="">someloooooooooooooooooooooong text </a></li>
  <li><a href="">someloooooooooooooooooooooong text </a></li>
  <li><a href="">someloooooooooooooooooooooong text </a></li>
  <li><a href="">someloooooooooooooooooooooong text </a></li>
</ul>


推荐阅读