Sami Al-Subhi Sami Al-Subhi - 5 months ago 11
CSS Question

centering a div is not working

I did the magic trick to center a div by giving it a

margin:--px auto
but it does not work. what could be the issue here?

https://jsfiddle.net/1zptxa7h/3/

<div class="single-view-container" style="display: block;">
<div id="single-view" class="single-view grid-100 grid-parent">center me</div>
</div>

.single-view-container {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
z-index: 3;
overflow: auto;
background: rgba(0, 0, 0, 0.3);
display: none;}

.single-view {
color: white;
max-width: 100px;
width: 100%;
display: inline-block;
margin: 20px auto;
height:100px;
background:red;
box-shadow: 0 2px 4px rgba(0,0,0,0.2),0 -1px 0px rgba(0,0,0,0.02);
border-radius: 2px;
padding-bottom: 10px;
}

Answer

The margin: 0 auto work on block elements with a fixed width, so if you change to display: block (or remove it completely as it is the default for a div) it will work as expected.

Side note: If to center an inline element (or inline-block), set text-align: center on its parent.

  .single-view-container {
      position: absolute;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      z-index: 3;
      overflow: auto;
      background: rgba(0, 0, 0, 0.3);
      display: none;}

  .single-view {
      color: white;
      max-width: 100px;
      width: 100%;
      display: block;
      margin: 20px auto;
      height:100px;
      background:red;
      box-shadow: 0 2px 4px rgba(0,0,0,0.2),0 -1px 0px rgba(0,0,0,0.02);
      border-radius: 2px;
      padding-bottom: 10px;
  }
<div class="single-view-container" style="display: block;">
     <div id="single-view" class="single-view grid-100 grid-parent">center me</div>
</div>