简体   繁体   中英

Centering Background Image Horizontally for Responsive Layout

I have two background images stacked on top of each other. Based on the results of an ajax call, the top image is slid up to reveal the image behind it. I have the following layout:

<div id="bg_before"><img class="bg_image"></div>
<div id="bg_after"><img class="bg_image"></div>

The image uploaded will vary based on what a user chooses. The CSS is as follows:

#bg_before, #bg_after {
    position: absolute;
    top: 0;
    left: 0;
    overflow: hidden;
    z-index: -10;
    width: 100%;
    height: 100%;
}

.bg_image {
    background-size: cover;
    overflow: hidden;
}

The image centers properly on a monitor (we recommend uploading an image 1920x1080). However, on a tablet or mobile I'd like the 1920x1080 image to fit centered, cropping the left and right of the image and keeping the height at 100%. I cannot seem to get this to work. I've tried transform, margin-left:-50% and background-position: center; to no avail.

Example at: http://cbotriage.bid/boards/appeal.php?item_id=569578

EDIT: I'm trying to shift a background image to the left so that the center of the background image lands in the center of the container div "bg_before" which is 100% width and 100% height of the display. Currently the background image is top left of the "bg_before" div no matter the resolution of the window.

Essentially I'm trying to make the background image center no matter the device (landscape/portrait).

Hello M Charles please use this css... like i did it

 #bg_before, #bg_after { position: absolute; top: 0; left: 0; overflow: hidden; z-index: -10; width: 100%; height: 100%; } .bg_image { background-size: cover; overflow: hidden; } #bg_before .bg_image { object-fit: cover; object-position: center; width: 100%; height: 100%; }
 <div id="bg_before"><img class="bg_image"></div> <div id="bg_after"><img class="bg_image"></div>

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