1

我正在尝试制作一个简单、流畅、响应式的两列布局(只是为了学习 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 中对其进行了测试,两者都发生了。

我已经创建了这个 JSFiddle,并且感谢 cimmanon 的评论,行为是相同的。

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

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

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

谢谢!

4

2 回答 2

1

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

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

于 2012-12-25T14:16:27.840 回答
1

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

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

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)。

于 2012-12-25T14:28:37.527 回答