css 为什么psudeo after元素的宽度与其父元素的宽度不相关?

gr8qqesn  于 2022-12-05  发布在  其他
关注(0)|答案(2)|浏览(141)

我试图添加一个下划线一样的符号下面的活动链接为这个目的,我使用::后元素,并设置它的宽度为100%,以获得其父元素的宽度,但psudo元素是大得多,当宽度为100%;
我html代码是👇

<header class="main-header">
  <a class="category-name">
    <span> Sneakers </span>
  </a>
  <nav class="main-nav">
    <ul class="main-nav-list">
      <li class="m">
        <a class="main-nav-link" href="#how">Collections</a>
      </li>
      <li><a class="main-nav-link" href="#meals">Men</a></li>
      <li>
        <a class="main-nav-link" href="#testimonials">Women</a>
      </li>
      <li><a class="main-nav-link" href="#pricing">About</a></li>
      <li><a class="main-nav-link nav-cta" href="#cta">Contact</a></li>
    </ul>
  </nav>
  <ul class="my__ac-list">
    <li class="nav--cart_icon" id="cartBtn">
      <a href="#" class="cart-icon"
        ><img src="./images/icon-cart.svg" alt="cart icon" srcset=""
      /></a>
      <p class="cart--strip">3</p>
    </li>
    <li>
      <a href="#">
        <img
          class="profile-thumbnail"
          src="./images/image-avatar.png"
          alt="image-avatar"
          srcset=""
        />
      </a>
    </li>
  </ul>
</header>

我的css代码是位长我不能正确格式化,所以我已经创建了包含我的html和css代码
代码结束链接= https://codepen.io/sinan-m/pen/abKQaxp
我想添加一个下划线下面的活动导航链接喜欢在设计
我的设计图像https://github.com/front-end-mentor-works/e-com-product-page/blob/main/design/active-states-basket-filled.jpg

jk9hmnmh

jk9hmnmh1#

.main-nav-list li.m for this selector you need to add position: relative. Beacause right now the after pseudoelement is not positioned relative to the li element.
position: absolute;
An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed).
However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.
Because you didn't set position:relative on the li, he after element takes the width of the window browser. That's why when set to 100%, it's so wide.

klsxnrf1

klsxnrf12#

结果

溶液

.main-nav-list li.m {
  border-bottom: 5px solid tomato;
}

我在代码笔中编辑了.main-nav-list li.m选择器的规则。
为了使它更有间隔,可以加一些填充物。

.main-nav-list li.m {
  border-bottom: 5px solid tomato;
  padding-bottom: 1ex;
}

您还需要更改

.main-nav-list {
  …
  align-items: top;
  …
}

保持良好的对齐。并删除黄色。

相关问题