具有100%高度保留宽高比的HTML背景图像

时间:2016-05-28 14:27:21

标签: html css twitter-bootstrap

我正在尝试使用bootstrap css模板和其他自定义css来填充页面。

HTML:

<head>
    <link rel="stylesheet" href="bootstrap.min.css" />
    <link rel="stylesheet" href="cover.css" />
</head>
<body>
    <div class="my_banner">
    <div class="col-lg-8">
    <h3>Title</h3>
    </div>
    <div class="col-lg-4 ">
    <a class="btn btn-success">Ok</a>
    </div>
    </div>
</body>

cover.css:

.my_banner {
    padding-top: 50px; 
    text-align: left;
    color: #f8f8f8;
    background: url(image.png); 
    max-width: 100%;
    height: auto;   
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
    background-repeat: no-repeat;
}

然而,当浏览器宽度较小时,图像仅填充页面高度的1/3,当浏览器宽度变大时,图像仅约为页面的1/10。如何才能让整个高度始终充满?

2 个答案:

答案 0 :(得分:3)

只需要将高度设置为100vh,这意味着您将填充浏览器的所有高度值

.my_banner{
    height: 100vh;
    background: url(image.png) center; 
    background-size: cover;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-repeat: no-repeat;
}

工作代码集示例:http://codepen.io/anon/pen/rLNyvw

答案 1 :(得分:0)

你也可以使用background-size属性,如:

` .my_banner {

padding-top: 50px; 

text-align: left;

color: #f8f8f8;

background: url(image.png); 

background-size: 100% 100%;

background-repeat: no-repeat;

}`