Paul
Paul

Reputation: 11746

Center span inside a div container over an image

I have images that are responsive in size and I'm trying to overlay a play icon in the center of them. I'm able to center the icon vertically but not horizontally.

See my jsfidde

HTML:

<div class="img-container">
  <img src="http://i.vimeocdn.com/video/503897818_640.jpg" style="width:315px;height:177px;">
  <div class="post-video-overlay-lg">
    <span class="glyphicon glyphicon-play" aria-hidden="true"></span>
  </div>
</div>

CSS:

.post-video-overlay-lg {
  position: absolute;
  font-size: 72px;
  color: #E5E5E5;
  text-align: center;
  width: 100%;
}

.img-container {
  position: relative;
  width:315px;
  height:auto;
  display:block;
  margin:auto;
  cursor:pointer;
}

Any idea what I'm missing?

Upvotes: 1

Views: 2210

Answers (2)

Paulie_D
Paulie_D

Reputation: 115108

Firstly you have to position the overlay div over the image/video..then position the span.

.post-video-overlay-lg {
    position: absolute;
    top:0;
    left:0;
    font-size: 72px;
    color: #E5E5E5;
    text-align: center;
    width: 100%;
    height: 100%;
}
.post-video-overlay-lg span {
    position: absolute;
    top:50%;
    left:50%;
    transform:translate(-50%, -50%);
}

.img-container {
    position: relative;
    margin: auto;
    width:315px;
    cursor:pointer;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
}

.img-container img {
    display: block;
}
<div class="img-container">
    <img src="http://i.vimeocdn.com/video/503897818_640.jpg" style="width:315px;height:177px;" />
    <div class="post-video-overlay-lg">
        <span class="glyphicon glyphicon-play" aria-hidden="true"></span>

    </div>
</div>

JSfiddle Demo

Upvotes: 3

Anupam Basak
Anupam Basak

Reputation: 1523

Here is the Fiddle: http://jsfiddle.net/f1becapq/3/

Updated the css for .post-video-overlay-lg

.post-video-overlay-lg {
    position: absolute;
    font-size: 72px;
    color: #E5E5E5;
    text-align: center;
    left: 0;
    right: 0;
    top: -webkit-calc(50% - 36px);    /* 36px = 72px/2 */
    top: -moz-calc(50% - 36px);
    top: calc(50% - 36px);
}

Used the CSS calc function to vertically align the div in runtime

Upvotes: 0

Related Questions