0

I have created a div tag with image in it , but I cannot force this div to display everything in center of the page :

#mydiv {
position: absolute;
height: auto;
width: 1000px;
min-height: 50px;
}
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<link rel="stylesheet" href="responsive-full-background-image.css">

</head>

<body>
<div id="mydiv"><img src="http://dummyimage.com/960x461/FF9900/fff" width="960" height="461" /></div> 
</body>

</html>
Richard Parnaby-King
  • 14,703
  • 11
  • 69
  • 129
iOS.Lover
  • 5,923
  • 21
  • 90
  • 162

6 Answers6

2

lover You should use % because then the image while stay in the middle on different screen resolutions.

#yourdiv{
position: absolute;
height: auto;
width: 30%; ( % = the with of your image)
margin-left: 35%; ( 1/2 of % left)
margin-right: 35%; ( 1/2 of % left)
}
Frank Winters
  • 193
  • 13
2

If it only needs to be horizontally centered, it can be as simple as.

http://jsfiddle.net/g4we9b7x/

body {
    text-align: center;
}
#mydiv {
    display: inline-block;
}

If it needs to be both centered, read this - how to center an element horizontally and vertically?

Overall, this is the easiest for centering both - http://jsfiddle.net/g4we9b7x/1/

#mydiv {
    transform: translateX(-50%) translateY(-50%);
    position: absolute;
    top: 50%;
    left: 50%;
}

http://caniuse.com/#feat=transforms2d

Community
  • 1
  • 1
Stickers
  • 75,527
  • 23
  • 147
  • 186
1

try text-align:center

#mydiv {
    background:orange;
    text-align:center;
    position: absolute;
    height: auto;
    width: 1000px;
    min-height: 50px;
}
<body>
    <div id="mydiv">
        <img src="https://placekitten.com/g/200/300" width="460px" height="461px" />
    </div>
</body>
Akshay
  • 14,138
  • 5
  • 46
  • 70
1

You want to put the image in the centre of the div? Use text-align:center;

Below I have replaced the width to 100% and made the image smaller to illustrate text-align:center;

#mydiv {
position: absolute;
height: auto;
width: 100%;
min-height: 50px;
  text-align:center;
}
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<link rel="stylesheet" href="responsive-full-background-image.css">

</head>

<body>
<div id="mydiv"><img src="http://dummyimage.com/96x46/FF9900/fff"  /></div> 
</body>

</html>
Richard Parnaby-King
  • 14,703
  • 11
  • 69
  • 129
0

This could be a difficult task depending on the rest of the layout. better read this article: http://www.smashingmagazine.com/2013/08/09/absolute-horizontal-vertical-centering-css/

herrfischer
  • 1,768
  • 2
  • 22
  • 35
0
position:absolute:
width:1000px;
height:500px;
top:50%;
margin-top:-250px; <!-- minus half the height of the box -->
laft:50%;
margin-left:-500px; <!-- minus half the width of the box -->

http://codepen.io/o0nico0o/pen/RNvzKy

o0nico0o
  • 41
  • 5