Cemil Tatoglu Cemil Tatoglu - 1 month ago 5
CSS Question

Absolute positioning for images within a div class

we have the following div structure, where we would like to horizontally center both the image and the text within the container div. However, the image is left aligned and only the title is centered.You could find the code below:



.QHeader {
position: absolute;
margin-top: 96px;
margin-left: 0px;
width: 800px;
height: 415px;
background-image: url('../img/bg_blue_rect.png');
background-repeat: no-repeat;
background-position: left top;
}
#QHeaderImg01 {
position: absolute;
display: block;
margin: 0 auto;
margin-top: 72px;
width: 263px;
height: 221px;
background-color: #0F0;
}
.QHeaderTitle {
position: absolute;
margin-top: 324px;
margin-left: 0;
width: 800px;
height: auto;
text-align: center;
font-family: Arial, Helvetica, sans-serif;
font-size: 30px;
font-weight: bold;
color: #000;
}

<div class="QHeader">
<img id="QHeaderImg01" src="img/q_header_img_01.png" />

<div class="QHeaderTitle">
TITLE
</div>
<!--QHeaderTitle-->

</div>
<!--QHeader-->




Answer

Just remove your position: absolute; or change it to position: relative;, as you will not need absolute positioning to horizontally center your elements:

.QHeader {
  width: 800px;
  height: 415px;
  background-image: url(http://placehold.it/800x415);
  background-repeat: no-repeat;
  background-position: left top;
}
#QHeaderImg01 {
  display: block;
  margin: 0 auto;
  width: 263px;
  height: 221px;
  background-color: #0F0;
}
.QHeaderTitle {
  margin-top: 50px;
  width: 800px;
  text-align: center;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 30px;
  font-weight: bold;
  color: #000;
}
<div class="QHeader">
  <img id="QHeaderImg01" src="http://placehold.it/263x221/0c0" />

  <div class="QHeaderTitle">
    TITLE
  </div>
  <!--QHeaderTitle-->

</div>
<!--QHeader-->