如何摆脱CSS中的水平滚动条

时间:2020-08-23 10:26:32

标签: css

我是CSS的新手,从事基础工作。所以只写了几行

  body {
                margin: 0;
                padding: 0; 
                width: 100%;    
                height: 100%;      
            }
            .one {
                width: 100vw;
                height: 100vh;
                background-image: url("pic.jpg");
                background-size: cover;
                background-repeat: no-repeat;
                background-position: center;
                position: relative;            
            } 
            
            .layer {
                position: absolute;
                width: 100%;
                height: 100%;
                background-color: rgba(0, 0, 0, 0.6);
            }          
            <div class="one">
                <div class="layer"></div>                     
            </div>         
            <div class="next">
                <h1>This is another para</h1>
            </div>

我检查它是否出现水平滚动条。我不知道这是为什么以及如何解决它。这只是为了练习。

2 个答案:

答案 0 :(得分:1)

您需要如下设置width中的.one

body {
            margin: 0;
            padding: 0; 
            width: 100%;    
            height: 100%;      
}
.one {
            width: 100%;
            height: 100vh;
            background-image: url("pic.jpg");
            background-size: cover;
            background-repeat: no-repeat;
            background-position: center;
            position: relative;           
} 
        
.layer {
            position: absolute;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.6);
}
<div class="one">
     <div class="layer"></div>                     
</div>         
<div class="next">
     <h1>This is another para</h1>
</div>

答案 1 :(得分:0)

之所以会出现此问题,是因为使用vw的计算也会考虑滚动条的大小。 要解决此问题,您可以使用width: calc(100vw - var(--scrollbarWidth))body { margin: 0; padding: 0; width: 100%; height: 100%; } .one { width: calc(100vw - var(--scrollbarWidth)); height: 100vh; background-image: url("https://images.pexels.com/photos/217872/pexels-photo-217872.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260"); background-size: cover; background-repeat: no-repeat; background-position: center; position: relative; } .layer { position: absolute; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.6); }

<div class="one">
            <div class="layer"></div>                     
        </div>         
        <div class="next">
         <h1>This is another para</h1>
 </div>
{{1}}

我希望它可以帮助您=)