简体   繁体   English

为什么一个绝对定位的元素会在这个侧边菜单中占据空间?

[英]Why does an absolutely positioned element take space in this side menu?

I am creating the following side menu with animation: click我正在使用 animation 创建以下侧边菜单:单击

We can see an unwanted horizontal scrollbar, which should not be according to developer.mozilla.org ,我们可以看到一个不需要的水平滚动条,这不应该是根据developer.mozilla.org

absolute

The element is removed from the normal document flow, and no space is created for the element in the page layout.该元素会从正常的文档流中移除,并且不会在页面布局中为该元素创建空间

In the example above, the list of menu appears when you click on the checkbox and it has the class .m-list .在上面的示例中,当您单击复选框时会出现菜单列表,其中包含 class .m-list .m-list has absolute positioning and relative positioning is set for its nearest parent( .m-block ). .m-list具有绝对定位,并且为其最近的父级( .m-block )设置了相对定位。 I'm going to copy and paste these two classes我要复制粘贴这两个类

.m-block {
      width: 100%;
      background: gray;
      padding: 0;
      display: flex;
      flex-direction: row-reverse;
      position: relative;
   }
   
   
   .m-list {
      position: absolute;
      top: 100%;
      background: silver;
      right: 0;
      width: auto;
      list-style-type: none; 
      transform: translateX(0%);
      transition: transform 0.25s ease-out;
   }

Q1: Why does the horizontal scrollbar appear? Q1:为什么会出现水平滚动条?

Q2: What is the most correct solution to prevent the appearance of a horizontal scrollbar? Q2:防止水平滚动条出现最正确的解决方案是什么?

I know 4 ways to solve this problem, but due to various reasons I do not want to use them:我知道解决这个问题的 4 种方法,但由于各种原因我不想使用它们:

  1. If I change the absolute position to a fixed one, it does not generate a horizontal scrollbar, but the rule line with top: 100%;如果我将绝对的 position 更改为固定的,它不会生成水平滚动条,而是生成带有top: 100%; takes on a different meaning.具有不同的含义。 In the original case, top: 100%;在原始情况下, top: 100%; provides an offset from the blue stripe along its height.沿其高度提供与蓝色条纹的偏移。

  2. Using JS is not available in this project本项目不支持使用JS

  3. Using overflow-x: hidden on the top level of document will disable the scrollbar, which may be needed for content.在文档的顶层使用overflow-x: hidden将禁用滚动条,这可能是内容所需要的。

  4. Moving the menu from the right side to the left will not result in a horizontal bar, however, this is an undesirable solution.将菜单从右侧移动到左侧不会产生水平条,但是,这是一个不受欢迎的解决方案。

     .m-list {... left: 0; transform: translateX(0%); } #m-toggle:checked ~.m-list {... transform: translateX(-100%); }

I tried applying overflow-x: hidden;我尝试应用overflow-x: hidden; to <body> .<body> and I was able to scroll down and hide the menu我能够向下滚动并隐藏菜单

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM