【问题标题】:Cant Center border bottom below dynamicallyCant 动态居中边框底部下方
【发布时间】:2021-05-14 10:54:34
【问题描述】:

我有一个简单的navbar,我通过ul 有几个菜单项,我想做的是每当我将鼠标悬停在li 上时,border-bottom 就会出现在@ 的center 987654326@ 但我首先遇到一些问题是border-bottom's 宽度离开了文本,有时它没有覆盖上面文本的完整width

body{

    margin: 0px;
    padding: 0px;
    background: #2c3e50;
}

.header__middle ul{
    
    list-style-type: none;
    display: flex;

}

.header__middle ul li a{


    margin-right: 10px;
    text-decoration: none;
    font-size: 1.2em;
    color: black;
    text-align: center;


}

.header__middle ul li {
    position: relative;
}

.header__middle ul li:hover ::after{
 
    content: "";
    position: absolute;
    left: 4%;
    bottom: -13%;
    width: 40px;    
    border-bottom: 2px solid black;
    }
            <div class="header__middle">
                <ul>
                    <li ><a href="#">Home</a></li>
                    <li><a href="#">Join</a></li>
                    <li><a href="#">FAQs</a></li>
                    <li><a href="#">About Us</a></li>
                </ul>
            </div>

HTML

【问题讨论】:

    标签: html css hover html-lists


    【解决方案1】:

    来,试试这个。我看到的唯一问题是您的 40px 边框对于“加入”等某些项目来说太宽了。 (注释在代码中)

    body {
      margin: 0px;
      padding: 0px;
      background: #2c3e50;
    }
    
    .header__middle ul{
      list-style-type: none;
      display: flex;
    }
    
    /* Remove your margin here and re-add it as a padding on the parent li */
    .header__middle ul li a{
      text-decoration: none;
      font-size: 1.2em;
      color: black;
      text-align: center;
    }
    
    .header__middle ul li {
      position: relative;
      padding-right: 10px;
    }
    
    /* Change to display block and position relative */
    .header__middle ul li:hover ::after{
      content: "";
      display: block;
      position: relative;
      left: calc(50% - 20px); /* To center, set your left for 50% minus half of your bar's width */
      width: 40px;
      border-bottom: 2px solid black;
    }
    
       <div class="header__middle">
           <ul>
               <li ><a href="#">Home</a></li>
               <li><a href="#">Join</a></li>
               <li><a href="#">FAQs</a></li>
               <li><a href="#">About Us</a></li>
           </ul>
       </div>
    

    编辑:对不起,我可能误解了。我以为您希望您的 40 像素条以每个对象为中心。

    如果你希望你的栏与每个项目的宽度相同,只需从我上面的代码中删除 left 和 width 属性,如下所示:

    .header__middle ul li:hover ::after{
      content: "";
      display: block;
      position: relative;
      border-bottom: 2px solid black;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      相关资源
      最近更新 更多