Search code examples
htmlcsscentering

How to center an element based on the parent div?


I am trying to add a big play button on top of a video.

The video itself is responsive, and I want the play button to always be centered horizontally and vertically within the video.

It will be something like

 ---------------------------
|                           |
|                           |
|   play button in center   |  <----video
|                           |
|                           |
 ---------------------------

I have something like:

<div style='text-align:center;'>
         <div id='playIcon'><img src='play.png'/></div> 
          <video id='video' >
              <source src=/video.mp4' type="video/mp4">
          </video>
        </div>
</div>

My css

#video{
   width:100%;
   max-height:1200px;
   z-index: 1;
   background-color: black;
}

How do I center the play button this case?


Solution

  • Here is a fiddle:

    http://jsfiddle.net/Bc4NP/

    You need to add position:relative to your main div:

    <div style="text-align:center; position:relative">
        <div id="playIcon"><img src="play.png" /></div> 
            <video id="video">
                <source src="/video.mp4" type="video/mp4">
            </video>
        </div>
    </div>
    

    And then, add this styles to your play button:

    #video{
       width:100%;
       max-height:1200px;
       z-index: 1;
       background-color: black;
    }
    #playIcon {
        position: absolute; 
        top: 47%;
        right: 0;
        bottom: 0;
        left: 0;
        margin: auto;
    }
    

    Now you get an exact horizontal center align, and almost-exact vertical align (you can be more precise changing top:47%)