【问题标题】:Margin of one element affecting the element at its side一个元素的边距影响其一侧的元素
【发布时间】:2012-12-25 13:53:00
【问题描述】:

我正在尝试制作一个简单、流畅、响应式的两列布局(只是为了学习 CSS),由侧边栏和主要部分组成。

我能够创建高度为 100% 的侧边栏,将主要内容放置在侧边,但是当我在主要部分中放置 H1 时... tada!它的边距也为侧边栏创建了边距。

下面是出现问题的最少代码:

<!DOCTYPE html>
<html>
  <head>
    <style>
      html,body {
        margin:0;
        padding:0;
        width:100%;
        height:100%;
      }

      #sidebar {
        display:block;
        position:absolute;
        width:25%;
        min-height:100%;
        border-right:1px solid #222;
        background-color: #E0E0E0;
      }

      #main {
        margin-left:25%;
        display:block;
      }

      h1 {
        padding:2%;
        /* margin:0; */
        /* defining the margin as zero aligns 
         * everything at the top */
      }
    </style>
  </head>

  <body>
    <header id="sidebar">
      Let's reach for the stars!
    </header>

    <section id="main">
      <h1>Nope!</h1>
    </section>

  </body>
</html>

我已经在 Chrome 和 Firefox 中测试过,两者都发生过。

I've created this JSFiddle,感谢 cimmanon 的评论,行为是相同的。

好吧,我迷路了。我错过了一些非常简单的东西吗?

这种方法是制作两列布局的好方法吗?我启发了自己阅读 Svbtle blogs 的 CSS。

如果不是,请以正确的方式向我灌输。我需要良好的 CSS 灌输 :)

谢谢!

【问题讨论】:

  • JSFiddle 默认添加了一个不正确地标记为“规范化”的重置。不规范化查看:jsfiddle.net/PmkCQ/2
  • 哦,不知道。在我的示例中,我依赖于 h1 有边距这一事实,而带有“规范化”的 jsFiddle 从 h1 中剥离了边距,谢谢!

标签: css two-columns


【解决方案1】:

一般来说,应避免使用绝对定位,除非您确实希望将元素从文档流中移除。如果您有一个页面,其中#main 的内容最终比#sidebar 短,并且用户的显示屏不够高,无法显示#sidebar 的所有内容,那么您的内容将被剪掉。

我最喜欢的实现等高列的方法是使用display: table CSS 属性。

http://jsfiddle.net/PmkCQ/3/

html,body {
        margin:0;
        padding:0;
        width:100%;
        height:100%;
      }

body { display: table }

      #sidebar {
        width:25%;
        border-right:1px solid #222;
        background-color: #E0E0E0;
      }

      #sidebar, #main {
        display:table-cell;
        vertical-align: top; /* optional */
      }

      h1 {
        padding:2%;
        margin-top: 0;
        /* margin:0; */
        /* defining the margin as zero aligns 
         * everything at the top */
      }

当然还有其他方法,但这种方法比浮动或绝对定位更脆弱。唯一的缺点是 IE7 不支持这些属性,因此它们将继续使用元素先前定义(或默认)的显示设置(对于div,它将是block)。

【讨论】:

    【解决方案2】:

    将display: inline-block添加到h1,它不会影响侧边栏。然后你可以设置任何你想要的边距。

    在 JSFiddle 中看起来不错的原因可能是从他们的样式中应用的样式(检查 h1,你会看到它有 margin:0)。

    【讨论】:

    • 谢谢,但你知道为什么它首先会影响它吗?即使使用 display:block 对我来说也没有意义(否则我对 CSS 中的显示如何工作有一个很大的误解)
    • 除此之外,更好的方法是将 display:inline-block 放在 section,而不是 h1,对吧?
    猜你喜欢
    • 2011-09-25
    • 1970-01-01
    • 2011-05-29
    • 2019-01-27
    • 2021-09-10
    • 2015-07-28
    相关资源
    最近更新 更多