以背景图像为中心的文字[CSS]

时间:2015-09-18 09:03:45

标签: javascript jquery html css

我希望有一个背景图像(在div中),它总是完全显示在屏幕上(宽度和高度为100%),文本位于div的中间,无论分辨率如何。 (见下文)绿色的div(#section_header)是背景图像的容器。

http://uprapide.com/image/1023303-stack

我正在使用JQuery来执行此操作,使用我想要显示的图像的比例(宽度/高度):

var resizeTimer; 

jQuery(window).resize(function() {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(resizeFunction, 250);
});

function resizeFunction()
{
// TO set the image background dimensions
var number = (jQuery(window).width()) ;
   jQuery('#section_header').height(number/2.88);

// TO put the text on the middle
   var element_w = parseInt(jQuery('#section_header').css('width'),10); 
   var element_w2 = element_w/2;
   var space_border = number - number/2 - element_w2;
   jQuery('.column.two-third.column_column.bg_section_header').css('border-spacing',space_border/2+'px 0px');

 }

和css

   #section_header {

    min-height: 255px;
    display: table-cell;
    vertical-align: middle;
}

.column.two-third.column_column.bg_section_header {
display: table;
width: 100%;
 }

此解决方案有效,但我想优化解决方案,因为加载速度非常慢。有什么建议?

谢谢

2 个答案:

答案 0 :(得分:1)

使用纯CSS可以做得更简单:

<强> HTML

<div class="container">
    <div class="middle-div">
        <p>TEXT</p>
    </div>
</div>

<强> CSS

.container { 
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  width: 100%;
  background: red
}

.middle-div {
   color: white; 
}

请参阅此处的工作示例: - EXAMPLE

修改

要使背景图像拉伸并调整到屏幕宽度,请将以下内容添加到主容器类中:

background: url(images/bg.jpg) no-repeat center center fixed; 
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;

*显然,您需要将url(images/bg.jpg)替换为您自己的图片。

答案 1 :(得分:0)

你的意思是这样吗?如果是这样,你不需要jquery。

<div class="mrBigAssWithCenter"> Center Text </div>

.mrBigAssWithCenter{
     width: 80%; 
     height:80%;
    min-height:100px;
    background:url('http://s3.wallippo.com/thumbs/300x250/black-background-metal-hole-small-0973bb47dba91f8d8959dd9e308cd3ae.jpeg') no-repeat;
    background-size:100%;
    text-align:center;
    border:1px solid #a1a1a1;
    color:#fff;
}

Fiddle