【问题标题】:css percentages height and widthCSS百分比高度和宽度
【发布时间】:2013-08-23 23:51:52
【问题描述】:

我了解,要使元素的高度达到视口的 100%,父元素必须具有固定的高度,或者 html 和主体的高度必须为 100%。

我的问题是我在屏幕中间有一个我想要的介绍标题,我想很简单,我会制作一个 100% 宽度和高度的 div,然后用户向下滚动以到达其余内容...没那么容易。为了使 div 的高度为 100%,我需要将 html 高度设置为 100%,但是当我这样做时,渐变背景会重复自身,因为它读取视口的高度(html 100%)而不是内容。

网站是here

代码:

<div class="intro">
   <div class="intro_text">
        <h2><?php the_title(); ?></h2>
        <h3><?php the_date('Y'); ?></h3>
   </div>
</div>

<div id="content">
   <!--The user scrolls down to see this-->
</div>

html {
width: 100%;
height: 100%;
}

body {
width: 100%;
height: 100%;
background-color: #004000;
background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#ec448c), to(#5a94bc));
background: -webkit-linear-gradient(top, #ec448c, #5a94bc);
background: -moz-linear-gradient(top, #ec448c, #5a94bc);
background: -ms-linear-gradient(top, #ec448c, #5a94bc);
background: -o-linear-gradient(top, #ec448c, #5a94bc);
}

.intro {
width: 100%;
height: 100%;
}

【问题讨论】:

  • 背景在哪里?

标签: html css


【解决方案1】:

您可以使用negative margin 技巧:

.intro { 
    height: 200px; 
    width: 200px; 
    position: absolute;
    top: 50%;
    left: 50%;
    margin: -100px 0 0 -100px;
}

只要所有祖先都没有位置,这将使 div 在视口中居中。诀窍是您将 div 放置在远离左上角的视口宽度和高度的 50% 处。然后,您只需在顶部和左侧边距中使用等于 .intro div 高度和宽度的一半的负边距(这将使 div 居中在新的中心点上)。

注意:如果您调整高度和宽度,您还应该调整负边距(例如,如果您将宽度更改为 300,负左边距应该是 150 - 宽度的一半)此外,这个技巧应该作为早在IE6,所以不用担心。

【讨论】:

    【解决方案2】:

    我对你的问题有点困惑,但如果你不想重复你的背景,你可以试试

    body { background:url(your_image.jpg) top no-repeat; background-position:fixed; }

    【讨论】:

      【解决方案3】:

      固定背景:不要将渐变应用到正文,而是使用另一个固定元素

      div#mybackground {
        position:fixed;
        top:0;
        left:0;
        right:0;
        bottom:0;
        z-index:-1;
        background: ..gradient..;
      }
      

      现在,您可以在您的网站上 。文字简介 { 高度:100%; } 然后使用 JavaScript,将 .intro_text 的行高设置为与 .intro_text 的高度相同的值,并将其添加到您的 h3 中:

      .intro_text h3 {
        position:relative;
        top: -90%;
      }
      

      top -90% 的更好替代方法是将 top 设置为 .intro_text 高度的负值

      【讨论】:

        【解决方案4】:

        将背景设置为html,并为其添加overflow: hidden。 然后将overflow: auto 添加到body

        Demo

        【讨论】:

          猜你喜欢
          • 2012-02-20
          • 1970-01-01
          • 2012-04-05
          • 2012-06-19
          • 2015-08-12
          • 2012-12-17
          • 2016-04-13
          相关资源
          最近更新 更多