user1386906
user1386906

Reputation: 1179

Align HTML element with background img positioned center

I have a background image center positioned on the body like so:

body {
    position:relative;
    width: 100%;
    height: 100%;
    background: url(../img/backgroundMd.jpg) no-repeat center center fixed #000; 
}

I want to align a div a part of the image. So it exactly covers it (on different screen resolutions)

div {
    position:absolute;
    width: 400px;
    height: 320px;
    background-color: black;
    top: ?
    left: ?
}

The backgroundMD.jpg is very large, so it goes off the screen. Thats why I can't make a wrapper div and center that. Any ideas?

Upvotes: 0

Views: 61

Answers (3)

Fury
Fury

Reputation: 4776

try to play with this dimension - this will help you to keep your element in middle of page

div {margin:0 auto;
     width:400px;
     height: 320px;
     background-color: black;}

Upvotes: -1

Nico O
Nico O

Reputation: 14152

Since you can not know how height the image in the background will be if it's scaled to the viewport. You will have to add the background as a <img> element. Like this:

http://jsfiddle.net/NicoO/dLBdv/

<div class="container">
    <div class="container-canvas">
        <p>Nice to sea you</p>
    </div>
    <img src="http://www.placehold.it/1000x500" /> 
</div>


.container
{
    position: relative;
}
.container > img
{
    max-width: 100%;
}

.container > .container-canvas
{
   background-color:blue;
   background-repeat: no-repeat;
   position: absolute;
   /* % to outer border */
   left:10%;
   top: 10%;
   bottom: 10%;
   right: 10%;
}

Upvotes: 0

pstenstrm
pstenstrm

Reputation: 6489

If the divs dimensions are fixed you can do something like this

div {
    position:absolute;
    width: 400px;
    height: 320px;
    background-color: black;
    top: 50%;
    left: 50%;
    margin: -200px 0 0 -165px;
}

Upvotes: 4

Related Questions