I have a div in which I'm trying to center an image. It centers perfectly if position is set to fixed, but when position is set to absolute, the image is a few pixels too much to the right.
I can't have position set to fixed because this div scrolls in from the top when the user clicks something, so I can't have it be visible until that moment. I've never had this problem before. Can anyone tell me what's wrong?
html:
<div class="header">
<img class="logo" src="img/navbar_title.jpg"/>
<img class="tab" src="img/mid_tab.png" /><!-- image to be centered -->
<div class="header_social">
<img src="img/button_pg.jpg" />
<img src="img/button_facebook.jpg" />
<img src="img/button_twitter.jpg" />
</div>
</div>
css:
.header
{
position:fixed;
top:-100px;
width:100%;
height:30px;
padding:10px;
background-color:black;
color: white;
z-index:10;
margin-top:0px;
box-shadow: gray 3px 0px 10px;
}
.header .logo
{
position: absolute;
top: 10px;
z-index: 4;
left: 20px;
}
.header .tab { /* not working right */
position: absolute;
top: 0;
z-index: 4;
left: 50%;
transform: translateX(-50%);
-moz-transform: translateX(-50%);
-ms-transform: translateX(-50%);
-webkit-transform: translateX(-50%);
}
.header h1
{
font-family: Helvetica, sans-serif;
font-weight: bold;
font-size:14pt;
display:inline-block;
line-height:30px;
float:left;
margin-top: 0;
margin-left: 20px;
letter-spacing: .05em;
color: #303030;
}
.header .header_social
{
float:right;
height:30px;
line-height:30px;
width:150px;
}
This is due to box-sizing. When you position fixed, it is relative to the entire screen, period. When you position absolute, it is relative to the nearest non-static position parent. In your case, that is your div.header. Your div.header has a padding and a width 100%, so it is actually 100% + 20. Set box-sizing: border-box on your div.header and your image will move a few pixels to the left. :)