Louis C. Louis C. - 3 months ago 7
CSS Question

Centre div inside another

I am having trouble centering content of one div inside of another because the content doesn't appear.



#searchbkg {
postition: relative;
width: 100%;
height: 700px;
background-color: #85e085;
}
#searchcentre {
position: absolute;
width: 50%;
margin: 0 auto;
}

<div id="searchbkg">
<div id="searchcentre">Test</div>
</div>





The green box appears but there is no text inside of it.

Answer

Your text is appearing fine, but it won't be centered because you have position: absolute; on the inside div. Change it to position: relative; and it will center horizontally. If you need the text to be centered within the div, you can also apply a text-align: center;.

#searchbkg {
  position: relative;
  width: 100%;
  height: 700px;
  background-color: #85e085;
}
#searchcentre {
  position: relative;
  width: 50%;
  margin: 0 auto;
  text-align: center;
  border: 1px solid red;
}
<div id="searchbkg">
  <div id="searchcentre">This is a centered div!</div>
</div>

Comments