html - 为什么CSS为两个div设置相同的宽度但显示不同的宽度

标签 html css width

<!DOCTYPE html>
<html>
<head>
<style>

这是宽度为 50% 的导航尺寸

#navigation {
    position: fixed;
    top: 110px;
    width: 50%;
    left:50%;
    margin-left:-25%;
    background: #FFF;
    z-index: 10000;
    height: 60px;
    opacity:0.7;
    padding:0;
    border-bottom:1px solid #ccc;
}

#navigation ul {
    list-style: none;
    padding:30px 0 0 0;
    margin:0;
}

#navigation ul li {
    font-weight:bold;
    color:#3d3d3d;
    float:left;
    padding:0 20px 0 0;
    margin:0;
}

这是内容的大小,宽度也是 50%

#content {
    position: relative;
    width: 50%;
    height: 100%;
    top:180px;
    left:50%;
    height:800px;
    margin-left:-25%;
    background-color: #3d3d3d;
    padding:0;
}
</style>
</head>

<body>
<div id="navigation">
    <ul>
        <li><a href="#">BUtton 1</a></li>
        <li><a href="#">BUtton 2</a></li>
            <li><a href="#">BUtton 3</a></li>
        <li><a href="#">BUtton 4</a></li>
    </ul>
</div>
<div id="content"></div>
</body>
</html>

我把navigation和content的宽度都设置为50%,但是当我在浏览器中打开时,这两个框的宽度不同,谁能帮帮我?

最佳答案

那是因为当您在 width 中设置 % 时,该元素会采用与其最接近的父元素相关的值。

当您为 #navigation 设置 position:fixed 时,这会使 html 成为他的父级,而 #contentbody 作为他的父级。这里的问题是,对于默认的 de html 标签有一个 padding 值,现在要使正文成为 html 等于并且 50% 宽度等于在你的 css 中设置它:

html, body {
  margin:0;
  padding:0;
}

在此处查看演示 http://jsfiddle.net/cAtgd/3/

关于html - 为什么CSS为两个div设置相同的宽度但显示不同的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19575240/

相关文章:

javascript - 在 Bootstrap 面板中旋转图像

javascript - JQuery UI 按钮的显示宽度不正确

java - 工具提示不换行/忽略最大宽度

html - 表单不会在 chrome 中提交

javascript - &lt;!-- 和//--> 在 Javascript 中有什么用?

css - 样式表在 docker 中从 nginx 提供,在页面上不可用

html - 如何将多个div居中并向左浮动?

ios - 具有不同数量项目的 CollectionView,项目应填充 Collection View

javascript - 在内容 Pane 中以 html 加载 javascript

html - CSS 100% 高度,然后滚动 DIV 不是页面