简体   繁体   中英

Text centered on a background image [CSS]

I would like to have a background image (in a div) which is always fully displayed on the screen (100 % for the width and height) with a text located on the middle of the div whatever the resolution. (see below) The div in green (#section_header) is the container of the background image.

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

I'm using JQuery to do this, using the ratio (width/height) of the image I want to display :

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');

 }

and the css

   #section_header {

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

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

This solution works, but I would like to optimize the solution, because it is pretty slow to load. Any advice?

Thank you

This can be done much simpler using purely 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; 
}

See working example here : - EXAMPLE

EDIT

To have the background image stretch and adjust to the screen width, add the following to your main container class :

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;

*Obviously you would need to replace url(images/bg.jpg) with your own image.

Did you mean something like this? If so you don't need jquery for that.

<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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM