【问题标题】:Adding a sidebar without changing alignment of main content添加侧边栏而不更改主要内容的对齐方式
【发布时间】:2017-02-14 12:50:05
【问题描述】:

我在网站上有页眉、页脚和主要内容。目前,它们具有自动边距并且宽度都相同,因此它们都很好地集中在页面上。

在网站上的某些但不是所有页面上,我希望在主要内容旁边显示一个侧边栏。我希望主要内容仍然与页眉和页脚对齐,并且所有内容都保持相同的宽度,但侧边栏出现在主要内容的右侧。换句话说,其他一切都应尽可能与没有侧边栏的情况相似。 所以侧边栏应该是这样的:

   |HEADER |
   |CONTENT| |SB|
   |CONTENT| |SB|
   |CONTENT|
   |FOOTER |

并且没有侧边栏:

   |HEADER |
   |CONTENT|
   |CONTENT|
   |CONTENT|
   |FOOTER |

有没有简单的方法用 CSS 做到这一点?

【问题讨论】:

    标签: html css


    【解决方案1】:

    提供侧边栏position 属性和以下值之一:

    • 已修复
    • 相对
    • 绝对的

    z-index: 1(或更高的值)。这将使侧边栏脱离正常的“流程”(relative 技术上除外)。

    参考文献

    在全页模式下查看代码段以获得更好的视图(尽管演示是响应式的,因此它仍可在较小的视口中运行)。点击红色的 Toggle 按钮。更多详细信息在下面的代码段中进行了评论。

    片段 1

    // This is not required; it's for demonstration
    
    var toggle = document.getElementById('sideToggle');
    
    toggle.addEventListener('click', function(event) {
      var sidebar = document.querySelector('aside');
      sidebar.classList.toggle('off');
    }, false);
    * {
      border-width: 1px;
      border-style: solid;
      border-color: black;
      background: rgba(0, 0, 0, .2);
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    html,
    body {
      font: 400 16px/1.45 Arial;
      height: 100%;
      width: 100%;
      border-color: lime;
    }
    ul {
      list-style: none;
    }
    header {
      border-color: #fff;
    }
    main {
      width: 70vw;
      padding: 3em 5vw;
      border: 5px dotted blue;
      margin: 0 auto;
    }
    article {
      padding: 1em 2em;
      border-color: salmon;
    }
    p {
      border-color: transparent;
      font-size: 1rem;
    }
    a {
      background: yellow;
    }
    /* Demo */
    
    #sideToggle {
      float: right;
      font: inherit;
      background: red;
      color: white;
      cursor: pointer;
      margin-right: 4em;
    }
    /* Required styles are preceded by ✎ */
    
    #sidebar {
      /* ✎ Use absolute or relative if "sticky"
      || behavior is not desired. Relative
      || will poisition itself relative to it's
      || original position. Absolute will
      || position itself in relation to the 
      || nearest positioned element, so it's
      || easier to use relative since you'll
      || need another positioned element to
      || position the sidebar. See reference
      || for more details.
      */
      position: fixed;
      /* ✎ See reference */
      z-index: 1;
      /* ✎ See reference */
      top: calc(50vh - 35px);
      /* ✎ See reference */
      right: 0;
      width: 20vw;
      height: auto;
      min-height: 70px;
      border: dashed red;
      background: rgba(255, 255, 255, .2);
    }
    /* Demo */
    
    .off {
      display: none;
    }
    <!doctype html>
    <html>
    
    <head>
      <meta charset='utf-8'>
    </head>
    
    <body>
      <header>
        <button id='sideToggle'>Toggle</button>
        <hgroup>
          <h1>H1 Title</h1>
          <h2>H2 Title</h2>
        </hgroup>
    
        <nav>
          <a href='#sec1'>Section 1</a>
          <a href='#sec2'>Section 2</a>
          <a href='#sec3'>Section 3</a>
        </nav>
    
      </header>
    
    
      <main>
        <!--BEGIN SIDEBAR-->
        <aside id='sidebar'>
          <h3>Sidebar</h3>
          <nav>
            <ul>
              <li><a href='#' target='_self'>Home Page</a>
              </li>
              <li><a href='http://example.com'>External Site</a>
              </li>
              <li><a href='#/'>Site Directory</a>
              </li>
            </ul>
          </nav>
        </aside>
        <!--END SIDEBAR-->
        <section id='sec1'>
          <article>
            <p>
              Chaugnar Faugn ph'grah'n Chaugnar Faugn wgah'n r'luh y-nglui Cthulhu ch', Nyarlathotep gotha mg hrii nog Nyarlathotep, llll goka uln uh'eagl Cthulhu sll'ha. Ph's'uhn Yoggoth Dagon gnaiih geb ebunma kadishtu n'ghft, nnnkadishtu Shub-Niggurath shtunggli
              nglui nnnuln tharanak ooboshu, ehyeog nnnHastur ya ep y-Chaugnar Faugn nogyar. Mg gotha Dagon naflr'luh f'ilyaa ftaghu s'uhn ooboshu f'ah Dagon, ehye athg fhtagnyar uaaah gnaiih phlegeth ah stell'bsna ngAzathoth, uln h''bthnk uaaahoth Cthulhu
              llll ngnglui bug y'hahor. Llll orr'eyar gof'nn Tsathoggua naflhrii Cthulhu shogg vulgtm naflkn'a lw'nafh nnnn'ghft, zhro ngn'ghft f'shogg r'luh f'Nyarlathotep chtenff bug syha'h naflchtenff naflkadishtu, cvulgtlagln stell'bsna zhro natharanak
              uaaah throd 'bthnk ngebunma bug.
            </p>
            <p>
              Wgah'n shogg hafh'drn ep y'hah kn'aoth ngtharanak shtunggli ee zhro wgah'n r'luh, nw ilyaa vulgtm zhro wgah'n k'yarnak ftaghu uaaah uln stell'bsnaog. Fm'latgh gotha f'stell'bsna stell'bsna y-uln gotha kadishtuagl gnaiih, Dagon h'chtenff sll'ha bug mg
              hupadgh cuh'e s'uhn, ah ebunma uaaah lloig y'hah Cthulhu. Uln ah wgah'n gof'nn ph'Azathoth hupadgh y-shogg, gof'nn ngn'gha kn'a ilyaa kadishtu, nanw fhtagn ah gotha mnahn'. Nghupadgh shtunggliagl n'gha czhro Yoggothog naflathg mg ch'or ehye
              vulgtlagln f's'uhn f'llll, ph'grah'n f'lw'nafh fm'latgh y'hah lw'nafhnyth ph'Azathoth nw Tsathoggua Cthulhu wgah'n, 'ai fm'latgh stell'bsna naflnglui naYoggoth 'aioth kadishtu nog r'luh f'ebunma.
            </p>
            <p>
              Sgn'wahl naflHastur sll'ha nnntharanak kn'a li'hee y-fhtagn, hupadgh bug y'hah Yoggoth Azathoth nw, orr'e y'hah stell'bsna f'syha'h syha'h. Naflooboshu k'yarnak shagg Shub-Niggurath shagg llll f'shugg nagnaiih, sgn'wahl s'uhn y'hah grah'n nasll'ha zhro
              cnilgh'ri hafh'drn, fm'latghyar ngsll'ha lw'nafh Azathoth llll cgof'nn. R'lyehog ch' y-mg gnaiih ngnw hrii vulgtm hai, athg naflhrii n'gha goka hrii uh'e, wgah'n ebunma uaaah s'uhn tharanak 'fhalma. 'bthnkor Dagon ph'llll fhtagn uh'e Dagon gnaiih
              f'shagg hafh'drn 'fhalma, vulgtlagln f'bug hai 'fhalma 'ai y'hahagl h'syha'h ya naflshagg llll, Chaugnar Faugn k'yarnak orr'e ph'gnaiih ph'nw tharanak ph'nglui ilyaa.
            </p>
            <p>
              Sll'haagl vulgtlagln uh'eog nnnmnahn' h'llll Shub-Niggurath ngthrod wgah'n ronyar hrii, h''ai tharanak zhro 'ai bug nachtenff ngluiog. Ebunma n'ghft chtenff gof'nn Dagon ron ilyaa hupadghoth, ep stell'bsna Shub-Niggurath nglui h'vulgtlagln phlegeth hupadgh
              li'hee, zhro Cthulhu uaaah vulgtlagln ee phlegeth. Nalw'nafh sgn'wahl kn'a chupadgh hrii ph'wgah'n grah'n f'n'gha Shub-Niggurathyar, 'fhalma nog ch' sgn'wahl Azathoth throd gotha n'gha, hafh'drn cs'uhn throd cshugg phlegeth s'uhn shtunggli.
              Fhtagn Cthulhu Azathothor Cthulhu Nyarlathotep ebunmaoth nafluln 'fhalma hai ngah, Azathoth shtunggli ch'agl f'nw naathg bug shagg nog Tsathoggua cgotha, nabug shtunggli mg ilyaa Dagon hafh'drn r'luh ep.
            </p>
            <p>
              Chaugnar Faugn gothaoth Nyarlathotep ron ep athg 'bthnk s'uhn phlegeth chai, syha'h sll'ha ph'Dagon f'nilgh'ri Chaugnar Faugn n'gha hlirghyar nglui, kn'a n'gha shagg hrii ebunma Tsathogguayar nnngoka f'nw. Geb orr'e kadishtu chtenffor shtunggli h'nog
              chtenffagl hrii gnaiih uln, fhtagn chtenff orr'eagl uln chtenff n'ghanyth hafh'drn ebunma Tsathoggua sll'ha, ron y-Yoggoth Cthulhu vulgtm uln ngR'lyeh Cthulhu ngehye. Y'hah bugyar wgah'n Azathoth zhro shtunggli f'shugg f'ftaghu ngathg geb shtunggli
              nachtenff naflli'hee, phlegeth Dagon n'gha ebunma throd r'luh gotha ngah sll'ha nglui. Lw'nafh ph'geb kn'a uln naYoggoth ebunma r'luh phlegeth Cthulhu ehye corr'e 'ai, Tsathoggua shagg ron f'nglui shagg li'hee goka wgah'n y-r'luh orr'e stell'bsna,
              nogog ngCthulhu mg nglui shugg fm'latgh h'hai hupadgh goka llll.
            </p>
            <p>
              S'uhn ee chtenff y-stell'bsna y-sgn'wahl athg hlirgh cAzathoth, Nyarlathotep Tsathoggua ebunma orr'e vulgtm Hastur, phlegethagl naflnog athg 'fhalma throd mnahn'.
            </p>
          </article>
        </section>
        <section id='sec2'>
          <article>
            <p>One morning, when Gregor Samsa woke from troubled dreams, he found himself transformed in his bed into a horrible vermin. He lay on his armour-like back, and if he lifted his head a little he could see his brown belly, slightly domed and divided
              by arches into stiff sections. The bedding was hardly able to cover it and seemed ready to slide off any moment.</p>
    
            <p>His many legs, pitifully thin compared with the size of the rest of him, waved about helplessly as he looked. "What's happened to me? " he thought. It wasn't a dream. His room, a proper human room although a little too small, lay peacefully between
              its four familiar walls.</p>
    
            <p>A collection of textile samples lay spread out on the table - Samsa was a travelling salesman - and above it there hung a picture that he had recently cut out of an illustrated magazine and housed in a nice, gilded frame. It showed a lady fitted
              out with a fur hat and fur boa who sat upright, raising a heavy fur muff that covered the whole of her lower arm towards the viewer.</p>
    
            <p>Gregor then turned to look out the window at the dull weather. Drops of rain could be heard hitting the pane, which made him feel quite sad. "How about if I sleep a little bit longer and forget all this nonsense", he thought, but that was something
              he was unable to do because he was used to sleeping on his right, and in his present state couldn't get into that position. However hard he threw himself onto his right, he always rolled back to where he was.</p>
    
            <p>He must have tried it a hundred times, shut his eyes so that he wouldn't have to look at the floundering legs, and only stopped when he began to feel a mild, dull pain there that he had never felt before. "Oh, God", he thought, "what a strenuous
              career it is that I've chosen! Travelling day in and day out. Doing business like this takes much more effort than doing your own business at home, and on top of that there's the curse of travelling, worries about making train connections, bad
              and irregular food, contact with different people all the time so that you can never get to know anyone or become friendly with them. It can all go to Hell! " He felt a slight itch</p>
          </article>
        </section>
        <section id='sec3'>
          <article>
            <p>"Lost by a whale! Young man, come nearer to me: it was devoured, chewed up, crunched by the monstrousest parmacetty that ever chipped a boat!&mdash;ah, ah!"</p>
    
            <p>I was a little alarmed by his energy, perhaps also a little touched at the hearty grief in his concluding exclamation, but said as calmly as I could, "What you say is no doubt true enough, sir; but how could I know there was any peculiar ferocity
              in that particular whale, though indeed I might have inferred as much from the simple fact of the accident."</p>
    
            <p>"Look ye now, young man, thy lungs are a sort of soft, d'ye see; thou dost not talk shark a bit. SURE, ye've been to sea before now; sure of that?"</p>
    
            <p>"Sir," said I, "I thought I told you that I had been four voyages in the merchant&mdash;"</p>
    
            <p>"Hard down out of that! Mind what I said about the marchant service&mdash;don't aggravate me&mdash;I won't have it. But let us understand each other. I have given thee a hint about what whaling is; do ye yet feel inclined for it?"</p>
          </article>
        </section>
      </main>
      <footer>
        <nav>
          <a href='#sec1'>Section 1</a>
          <a href='#sec2'>Section 2</a>
          <a href='#sec3'>Section 3</a>
        </nav>
      </footer>
    </body>
    
    </html>

    片段 2

    // This is not required; it's for demonstration
    
    var toggle = document.getElementById('sideToggle');
    var expand = document.getElementById('expand');
    var reduce = document.getElementById('reduce');
    var counter = 0;
    
    toggle.addEventListener('click', function(event) {
      var sidebar = document.querySelector('aside');
      sidebar.classList.toggle('off');
    }, false);
    
    expand.addEventListener('click', function(event) {
      var sec1 = document.querySelector('#sec1');
      counter += 5;
      sec1.style.marginLeft = counter + 'px';
      sec1.style.marginRight = counter + 'px';
    }, false);
    
    reduce.addEventListener('click', function(event) {
      var sec1 = document.querySelector('#sec1');
      counter -= 5;
      sec1.style.marginLeft = counter + 'px';
      sec1.style.marginRight = counter + 'px';
    }, false);
    * {
      border-width: 1px;
      border-style: solid;
      border-color: black;
      background: rgba(0, 0, 0, .2);
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    html,
    body {
      font: 400 16px/1.45 Arial;
      height: 100%;
      width: 100%;
      border-color: lime;
    }
    ul {
      list-style: none;
    }
    header {
      border-color: #fff;
    }
    main {
      width: 70vw;
      padding: 3em 5vw;
      border: 5px dotted blue;
      margin: 0 auto;
      box-sizing: content-box;
    }
    article {
      padding: 1em 2em;
      border-color: salmon;
    }
    p {
      border-color: transparent;
      font-size: 1rem;
    }
    a {
      background: yellow;
    }
    /* Demo */
    
    #sideToggle,
    #expand,
    #reduce {
      float: right;
      font: inherit;
      background: red;
      color: white;
      cursor: pointer;
      margin-right: 4em;
    }
    /* Required styles are preceded by ✎ */
    
    /* Styles that have been changed are preceded by ✦ */
    
    #sidebar {
      /* ✎ Use absolute or relative if "sticky"
      || behavior is not desired. Relative
      || will position itself relative to it's
      || original position. Absolute will
      || position itself in relation to the 
      || nearest positioned element, so it's
      || easier to use relative since you'll
      || need another positioned element to
      || position the sidebar. See reference
      || for more details.
      */
      /* ✦ */
      position: absolute;
      /* ✎ See reference */
      z-index: 1;
      /* ✦ See reference */
      top: 2%;
      /* ✦ See reference */
      right: -20vw;
      width: 20vw;
      height: auto;
      min-height: 70px;
      border: dashed red;
      background: rgba(255, 255, 255, .2);
    }
    .off {
      display: none;
    }
    section {
      /* ✦ */
      box-sizing: content-box;
      /* ✦ */
      position: relative;
      /* ✦ */
      width: 100%;
    }
    <!doctype html>
    <html>
    
    <head>
      <meta charset='utf-8'>
    </head>
    
    <body>
      <header>
        <button id='expand'>Expand</button>
        <button id='reduce'>Reduce</button>
        <button id='sideToggle'>Toggle</button>
        <hgroup>
          <h1>H1 Title</h1>
          <h2>H2 Title</h2>
        </hgroup>
    
        <nav>
          <a href='#sec1'>Section 1</a>
          <a href='#sec2'>Section 2</a>
          <a href='#sec3'>Section 3</a>
        </nav>
    
      </header>
    
    
      <main id='main'>
    
        <!--SIDEBAR IS MOVED INTO #SEC1-->
        <section id='sec1'>
          <!--BEGIN SIDEBAR-->
          <aside id='sidebar'>
            <h3>Sidebar</h3>
            <nav>
              <ul>
                <li><a href='#' target='_self'>Home Page</a>
                </li>
                <li><a href='http://example.com'>External Site</a>
                </li>
                <li><a href='#/'>Site Directory</a>
                </li>
              </ul>
            </nav>
          </aside>
          <!--END SIDEBAR-->
          <article>
            <p>
              Chaugnar Faugn ph'grah'n Chaugnar Faugn wgah'n r'luh y-nglui Cthulhu ch', Nyarlathotep gotha mg hrii nog Nyarlathotep, llll goka uln uh'eagl Cthulhu sll'ha. Ph's'uhn Yoggoth Dagon gnaiih geb ebunma kadishtu n'ghft, nnnkadishtu Shub-Niggurath shtunggli
              nglui nnnuln tharanak ooboshu, ehyeog nnnHastur ya ep y-Chaugnar Faugn nogyar. Mg gotha Dagon naflr'luh f'ilyaa ftaghu s'uhn ooboshu f'ah Dagon, ehye athg fhtagnyar uaaah gnaiih phlegeth ah stell'bsna ngAzathoth, uln h''bthnk uaaahoth Cthulhu
              llll ngnglui bug y'hahor. Llll orr'eyar gof'nn Tsathoggua naflhrii Cthulhu shogg vulgtm naflkn'a lw'nafh nnnn'ghft, zhro ngn'ghft f'shogg r'luh f'Nyarlathotep chtenff bug syha'h naflchtenff naflkadishtu, cvulgtlagln stell'bsna zhro natharanak
              uaaah throd 'bthnk ngebunma bug.
            </p>
            <p>
              Wgah'n shogg hafh'drn ep y'hah kn'aoth ngtharanak shtunggli ee zhro wgah'n r'luh, nw ilyaa vulgtm zhro wgah'n k'yarnak ftaghu uaaah uln stell'bsnaog. Fm'latgh gotha f'stell'bsna stell'bsna y-uln gotha kadishtuagl gnaiih, Dagon h'chtenff sll'ha bug mg
              hupadgh cuh'e s'uhn, ah ebunma uaaah lloig y'hah Cthulhu. Uln ah wgah'n gof'nn ph'Azathoth hupadgh y-shogg, gof'nn ngn'gha kn'a ilyaa kadishtu, nanw fhtagn ah gotha mnahn'. Nghupadgh shtunggliagl n'gha czhro Yoggothog naflathg mg ch'or ehye
              vulgtlagln f's'uhn f'llll, ph'grah'n f'lw'nafh fm'latgh y'hah lw'nafhnyth ph'Azathoth nw Tsathoggua Cthulhu wgah'n, 'ai fm'latgh stell'bsna naflnglui naYoggoth 'aioth kadishtu nog r'luh f'ebunma.
            </p>
            <p>
              Sgn'wahl naflHastur sll'ha nnntharanak kn'a li'hee y-fhtagn, hupadgh bug y'hah Yoggoth Azathoth nw, orr'e y'hah stell'bsna f'syha'h syha'h. Naflooboshu k'yarnak shagg Shub-Niggurath shagg llll f'shugg nagnaiih, sgn'wahl s'uhn y'hah grah'n nasll'ha zhro
              cnilgh'ri hafh'drn, fm'latghyar ngsll'ha lw'nafh Azathoth llll cgof'nn. R'lyehog ch' y-mg gnaiih ngnw hrii vulgtm hai, athg naflhrii n'gha goka hrii uh'e, wgah'n ebunma uaaah s'uhn tharanak 'fhalma. 'bthnkor Dagon ph'llll fhtagn uh'e Dagon gnaiih
              f'shagg hafh'drn 'fhalma, vulgtlagln f'bug hai 'fhalma 'ai y'hahagl h'syha'h ya naflshagg llll, Chaugnar Faugn k'yarnak orr'e ph'gnaiih ph'nw tharanak ph'nglui ilyaa.
            </p>
            <p>
              Sll'haagl vulgtlagln uh'eog nnnmnahn' h'llll Shub-Niggurath ngthrod wgah'n ronyar hrii, h''ai tharanak zhro 'ai bug nachtenff ngluiog. Ebunma n'ghft chtenff gof'nn Dagon ron ilyaa hupadghoth, ep stell'bsna Shub-Niggurath nglui h'vulgtlagln phlegeth hupadgh
              li'hee, zhro Cthulhu uaaah vulgtlagln ee phlegeth. Nalw'nafh sgn'wahl kn'a chupadgh hrii ph'wgah'n grah'n f'n'gha Shub-Niggurathyar, 'fhalma nog ch' sgn'wahl Azathoth throd gotha n'gha, hafh'drn cs'uhn throd cshugg phlegeth s'uhn shtunggli.
              Fhtagn Cthulhu Azathothor Cthulhu Nyarlathotep ebunmaoth nafluln 'fhalma hai ngah, Azathoth shtunggli ch'agl f'nw naathg bug shagg nog Tsathoggua cgotha, nabug shtunggli mg ilyaa Dagon hafh'drn r'luh ep.
            </p>
            <p>
              Chaugnar Faugn gothaoth Nyarlathotep ron ep athg 'bthnk s'uhn phlegeth chai, syha'h sll'ha ph'Dagon f'nilgh'ri Chaugnar Faugn n'gha hlirghyar nglui, kn'a n'gha shagg hrii ebunma Tsathogguayar nnngoka f'nw. Geb orr'e kadishtu chtenffor shtunggli h'nog
              chtenffagl hrii gnaiih uln, fhtagn chtenff orr'eagl uln chtenff n'ghanyth hafh'drn ebunma Tsathoggua sll'ha, ron y-Yoggoth Cthulhu vulgtm uln ngR'lyeh Cthulhu ngehye. Y'hah bugyar wgah'n Azathoth zhro shtunggli f'shugg f'ftaghu ngathg geb shtunggli
              nachtenff naflli'hee, phlegeth Dagon n'gha ebunma throd r'luh gotha ngah sll'ha nglui. Lw'nafh ph'geb kn'a uln naYoggoth ebunma r'luh phlegeth Cthulhu ehye corr'e 'ai, Tsathoggua shagg ron f'nglui shagg li'hee goka wgah'n y-r'luh orr'e stell'bsna,
              nogog ngCthulhu mg nglui shugg fm'latgh h'hai hupadgh goka llll.
            </p>
            <p>
              S'uhn ee chtenff y-stell'bsna y-sgn'wahl athg hlirgh cAzathoth, Nyarlathotep Tsathoggua ebunma orr'e vulgtm Hastur, phlegethagl naflnog athg 'fhalma throd mnahn'.
            </p>
          </article>
        </section>
        <section id='sec2'>
          <article>
            <p>One morning, when Gregor Samsa woke from troubled dreams, he found himself transformed in his bed into a horrible vermin. He lay on his armour-like back, and if he lifted his head a little he could see his brown belly, slightly domed and divided
              by arches into stiff sections. The bedding was hardly able to cover it and seemed ready to slide off any moment.</p>
    
            <p>His many legs, pitifully thin compared with the size of the rest of him, waved about helplessly as he looked. "What's happened to me? " he thought. It wasn't a dream. His room, a proper human room although a little too small, lay peacefully between
              its four familiar walls.</p>
    
            <p>A collection of textile samples lay spread out on the table - Samsa was a travelling salesman - and above it there hung a picture that he had recently cut out of an illustrated magazine and housed in a nice, gilded frame. It showed a lady fitted
              out with a fur hat and fur boa who sat upright, raising a heavy fur muff that covered the whole of her lower arm towards the viewer.</p>
    
            <p>Gregor then turned to look out the window at the dull weather. Drops of rain could be heard hitting the pane, which made him feel quite sad. "How about if I sleep a little bit longer and forget all this nonsense", he thought, but that was something
              he was unable to do because he was used to sleeping on his right, and in his present state couldn't get into that position. However hard he threw himself onto his right, he always rolled back to where he was.</p>
    
            <p>He must have tried it a hundred times, shut his eyes so that he wouldn't have to look at the floundering legs, and only stopped when he began to feel a mild, dull pain there that he had never felt before. "Oh, God", he thought, "what a strenuous
              career it is that I've chosen! Travelling day in and day out. Doing business like this takes much more effort than doing your own business at home, and on top of that there's the curse of travelling, worries about making train connections, bad
              and irregular food, contact with different people all the time so that you can never get to know anyone or become friendly with them. It can all go to Hell! " He felt a slight itch</p>
          </article>
        </section>
        <section id='sec3'>
          <article>
            <p>"Lost by a whale! Young man, come nearer to me: it was devoured, chewed up, crunched by the monstrousest parmacetty that ever chipped a boat!&mdash;ah, ah!"</p>
    
            <p>I was a little alarmed by his energy, perhaps also a little touched at the hearty grief in his concluding exclamation, but said as calmly as I could, "What you say is no doubt true enough, sir; but how could I know there was any peculiar ferocity
              in that particular whale, though indeed I might have inferred as much from the simple fact of the accident."</p>
    
            <p>"Look ye now, young man, thy lungs are a sort of soft, d'ye see; thou dost not talk shark a bit. SURE, ye've been to sea before now; sure of that?"</p>
    
            <p>"Sir," said I, "I thought I told you that I had been four voyages in the merchant&mdash;"</p>
    
            <p>"Hard down out of that! Mind what I said about the marchant service&mdash;don't aggravate me&mdash;I won't have it. But let us understand each other. I have given thee a hint about what whaling is; do ye yet feel inclined for it?"</p>
          </article>
        </section>
      </main>
      <footer>
        <nav>
          <a href='#sec1'>Section 1</a>
          <a href='#sec2'>Section 2</a>
          <a href='#sec3'>Section 3</a>
        </nav>
      </footer>
    </body>
    
    </html>

    【讨论】:

    • 这行得通!但是有没有办法让侧边栏“拥抱”主要内容而不是视图的右侧?我希望内容在展开时保持相同的宽度,并且边距会增加,因此当视图变得太小而无法同时显示内容和侧边栏时,您会获得水平滚动,并且侧边栏与主要内容保持一致边距向右增长。
    • 这是一个奇特的布局。见片段 2
    【解决方案2】:

    在主分区的样式表中开发两个类。 每当您希望边栏与主边栏一起使用时,请使用 width 属性来定义主边栏和边栏。

    只要您需要侧边栏,就可以在类之间切换。 参考下面的代码。

        header, footer {
            width: 100%;
            text-align: center;
            background: #aaa;
            padding: 10px 0px;
        }
        section {
            width: 100%;
            overflow: auto;
        }
        section div {
            float: left;
        }
        .only-main, .main-with-sidebar {
            height: 200px;
            text-align: center;
        }
        .only-main {
            width: 100%;
        }
        .main-with-sidebar {
            width: 70%;
            border: 1px solid green;
        }
    
        /************ For sidebar ***********/
        .sidebar {
            width: 29%;
            height: 200px;
            border: 1px solid red;
        }
        .hide {
            display: none;
        }
    <header>
    <h1>Header</h1>
    </header>
    <section>
        <div class="only-main">Main</div>
        <div class="sidebar hide">Sidebar</div>
    </section>
    <section>
        <div class="main-with-sidebar">Main</div>
        <div class="sidebar">Sidebar</div>
    </section>
    <footer>Footer</footer>

    【讨论】:

    • 这很好,但是当有侧边栏时,有没有办法使页眉/页脚与 Main 大小相同?此外,理想情况下,添加侧边栏时 Main(和其他部分)不会改变大小
    • 是的,可以做到。您必须使用 max-width 属性将布局限制为所有主要内容(页眉、主要和页脚),然后在布局外使用侧边栏。
    【解决方案3】:

    我改了一点,你可以看看。 要将侧边栏附加到主分区,您需要将部分宽度设置为 100% 并将主分区设置在中心。

    这里,我对侧边栏使用了绝对定位,所以我需要先将相对位置放在部分样式中。

    header, footer {
        width: 60%;
        text-align: center;
        background: #aaa;
        padding: 10px 0px;
        margin: auto;
    }
    section {
        position: relative;
        width: 100%;
        overflow: auto;
    }
    section div {
        float: left;
    }
    .only-main, .main-with-sidebar {
        height: 200px;
        width: 60%;
        text-align: center;
        margin-left: 20%;
        border: 1px solid green;
    }
    
    /************ For sidebar ***********/
    .sidebar {
        position: absolute;
        width: 19%;
        left: 80%;
        height: 200px;
        border: 1px solid red;
    }
    .hide {
        display: none;
    }
    <header>
    <h1>Header</h1>
    </header>
    <section>
        <div class="only-main">Main</div>
        <div class="sidebar hide">Sidebar</div>
    </section>
    <section>
        <div class="main-with-sidebar">Main</div>
        <div class="sidebar">Sidebar</div>
    </section>
    <footer>Footer</footer>

    【讨论】:

      猜你喜欢
      • 2019-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-22
      • 2018-11-19
      • 1970-01-01
      相关资源
      最近更新 更多