【问题标题】:how could one use percentage for the header when the width for the body hasn't been set当正文的宽度尚未设置时,如何为标题使用百分比
【发布时间】:2020-04-30 18:06:47
【问题描述】:

这是html:

<body>
  <!-- Forked from a template on Tutorialzine: https://tutorialzine.com/2016/06/freebie-landing-page-template-with-flexbox -->
  <header>
    <h2><a href="#">Mountain Travel</a></h2>
    <nav>
      <li class="new"><a href="#">Tours</a></li>
      <li><a href="#">About</a></li>
      <li><a href="#">Contact</a></li>
    </nav>
  </header>

  <section class="hero">
    <div class="go_crazy"></div>
    <div class="background-image" style="background-image: url(assets/img/main.jpg);" >
    </div>
    <div class="hero-content-area">
      <h1>Mountain Travel</h1>
      <h3>Unmissable Adventure Tours Around The World</h3>
      <span class="old"><a href="#" class="btn">Contact Us Now</a></span>
    </div>
  </section>

</body>

这是 CSS:

/*Header Styles*/

header {
    position: absolute;
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 35px 100px 0;
    animation: 1s fadein 0.5s forwards;
    opacity: 0;
    color: #fff;
}

CSS文件里面没有设置body的宽度,但是为什么开发者可以用100%的header呢? 我认为这意味着父级宽度的 100%。那么谁能帮我解释一下?

【问题讨论】:

    标签: html css width percentage


    【解决方案1】:

    浏览器自动设置&lt;body&gt;元素的宽度等于浏览器窗口的宽度。

    示例:如果您的浏览器窗口为 800px 宽,您可以想象浏览器插入了以下 CSS:

    body {
      width: 800px;
    }
    

    您无法在自己的代码中看到该 CSS,但它就在那里,隐藏在浏览器中。所以你认为将&lt;header&gt; 设置为 100% 宽度意味着它应该是父级宽度的 100% 是正确的,这就是在这种情况下有效的原因。

    【讨论】:

    • 非常感谢!我觉得不开心,因为教程没有告诉我这个,这让我很困惑,浪费了我很多时间
    • @renesmith 不客气!是的,我理解这种沮丧。不幸的是,这是教程中经常忽略的细节,无论是错误的还是无知的。有可能作者从来没有想过这个小细节,或者他们知道太久了,他们认为这是理所当然的,忘记了。无论哪种方式,这是一个很好的问题,如果您将来遇到类似问题,这里的人应该很乐意帮助回答类似的问题。
    • 这是否意味着该值是灵活的?我的意思是我总是可以改变浏览器的宽度,所有元素的宽度都会随之改变?
    • 没错!浏览器会在您调整其大小时更新隐藏的 width 值,这将导致所有子级也更新,依此类推。
    猜你喜欢
    • 2023-04-07
    • 2013-03-12
    • 2011-01-08
    • 2013-03-24
    • 2012-10-03
    • 1970-01-01
    • 2013-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多