html - css float 在顶部获得双边距(不是来自 body )

标签 html css double margin

我是 css 的新手,我遇到了一个浮点元素的边距问题,它在顶部有 20 像素的边距,即使它的边距是 10 像素。 我一直在研究几个主题, body 默认边距似乎是问题所在,但事实并非如此。任何人都知道为什么会出现这种双重 margin ?

我认为这是由于我的 div 容器在侧面,因为如果我将其上边距设置为 0,则 float 元素的上边距通常为 10 像素(而不是 20 像素)。我只是不明白 div 如何影响 float 元素。

ps: 我用的是火狐

double margin

html:

<body>
<nav>
    <ul>
        <li> <a href="">Home</a> </li>
        <li> <a href="">Products</a> </li>
        <li> <a href="">Plan B</a> </li>
    </ul>
</nav>
<div class="content">
    <h2> Products</h2>
    <ul>
        <li><a href="">Product category</a></li><!--
      --><li><a href="">Product category</a></li><!--
      --><li><a href="">Product category</a></li><!--
       --><li><a href="">Product category</a></li><!--
       --><li><a href="">Productcategory</a></li><!--
--></ul>
    <p>hello there!
       etc..</p>
</div>
</body>

CSS:

body {
    font-size: 14px;
    padding: 0;
    margin: 0;
    border; 0;
}

/* -------------- SIDEBAR ---------------- */

nav ul {
    float: left;
    display: inline-block;
    width: 180px;
    border: 0;
    margin: 0;
    padding: 0;
}

nav ul li {
    background-color: red;
    margin: 10px;               /* HERE */
    padding: 10px;
    list-style-type: none;
    text-align: center;
}

nav ul li a {
    color:black;
    padding: 0;
    bordeR; 0;
    text-decoration: none;
}



/* --------------CONTENT AREA---------------- */
div.content {
    background-color: blue;
    margin: 10px 10px 10px 180px;   /* if top margin set to 0, it works */
    padding: 0;
    overflow: hidden;
}

div.content h2 {
    font-size: 120%;
    padding: 0;
    margin: 5px;
    float: left;
}

div.content ul {
    list-style-type: none;
    padding: 0;
    margin: 0;
    float: right;
}

div.content ul li {
    display: inline-block;
    margin: 0;
    padding: 0;
}


div.content ul li a {
    background-color: pink;
    text-decoration: none;
    padding: 5px;
    border-radius: 0;
    border: black;
    border-style: solid;
    border-width: 0;
}

div.content p {
    font-size: 110%;
    clear: both;
}

提前致谢!

最佳答案

你对所有的人都有 margin ......这样做:

nav ul li:first-child {
    margin-top: 0;
}

当你使用 :first-child 时,你的第一个 li margin-top 是 0

关于html - css float 在顶部获得双边距(不是来自 body ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34906315/

相关文章:

javascript - 如何获取 svgElement 的比例?

html - 使用 XSLT 获取元素的所有文本,而不考虑标签

java - 字符串精度加倍

谁能解释一下输出

html - 你能在构建时美化 jekyll html 输出吗

html - 如何对齐表头列和表体列的宽度?

css - 保持第一个元素垂直居中,下一个元素在下面

html - 背景图像未使用 CSS 显示

java - 我的 split() 及其正则表达式有什么问题?

html - 元素的 z-index 但是不同的定位?