首页 > 解决方案 > Div 不断添加不必要的边距

问题描述

我的网站中有一个导航栏 div。有时它会停留在顶部,有时它会增加不必要的 margin-top。我不确定出了什么问题。我检查了我的网站,它没有与我的任何 div 的任何边距一起崩溃。我很困扰。我尝试使用位置,但没有奏效。任何人都可以帮忙吗?这是我的代码片段:

        .container-navbar{
           background-color: #ffffff;
           height: 60px;
           display: flex;
           justify-content: space-between;
           box-shadow: 0 0 20px rgba(0, 0, 0, 0.15);
           transition:5s;
        }
        .button-collapse-sidebar{
            padding-top: 10px;
            padding-left: 10px;
        }
        .button-collapse-sidebar button{
            height: 40px;
            width: 60px;
            font-size: 20px;
            border:none;
            background-color: blue;
            color: #ffffff;
        }
        .button-collapse-sidebar button:hover{
            transition: 1.5s;
            cursor: pointer;
            background-color: rgb(0,0,0); 
            background-color: rgba(0,0,0,0.4);
            z-index: 2;
        }
        .user{
            display: flex;
        }
        .user-name{
            padding: 18px;
        }
        .user-name i{
            padding-left: 5px;
        }
        .user-name i,a{
            text-decoration: none;
        }
        .user-picture{
            margin-top:5px;
            margin-right: 5px;
            width: 60px;
            position: relative;
            overflow: hidden;
            border-radius: 50%;
            height: 50px;
        }

        .user-picture img{
            width: 100%;
            margin: auto;
            position: absolute;
            top: 20px;
            bottom: 0;
        }
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <div class="container-navbar">
        <div class="button-collapse-sidebar">
            <button class="button-collapse"><i class="fa fa-bars" aria-hidden="true"></i></button>
        </div>
        <div class="user">
            <div class="user-name">
                <a href="">Admin name<i class="fas fa-circle"></i></a>
            </div>
            <div class="user-picture">
                <img src="" alt="user-picture">
            </div>
        </div>
    </div>
</body>
</html>

所以我更新了代码并添加了 body{ margin:0; 在这里,我有 2 个不同的文件 html,但具有相同的 html 标签和 css,但由于某种原因,我的主要文件无法正常工作,但我的测试 html 可以正常工作,并且没有添加不必要的边距顶部。

这个不工作

这一项工作

标签: htmlcss

解决方案


当浏览器呈现 HTML 页面时,它会在您编写单一样式之前应用基本样式。

例如,所有浏览器中的<h1>to <h6>HTML 标签与普通文本不同:通常,它们的字体更大,它们的字体粗细是粗体(font-weight: bold),并且它们在顶部和底部都有边距。

虽然所有浏览器都应用它们的基本样式,但每个浏览器都有其与其他浏览器不同的特定样式,这当然会导致不一致的问题。这就是你在这个问题中谈论的问题。解决浏览器不一致问题的尝试产生了两种方法:Normalize CSS方法和CSS Reset 方法


推荐阅读