css百分比高度和宽度

时间:2013-08-21 14:32:26

标签: html css

据我所知,为了使元素高度为视口的100%,父元素必须具有固定的高度,或者html和body的高度为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%;
}

4 个答案:

答案 0 :(得分: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,所以不用担心。

答案 1 :(得分:0)

修复背景:不使用渐变到主体,而是使用其他固定元素

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%;
}

更好的替代前-90%将设置.intro_text

的高度的负值。

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

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

Demo

相关问题