center a paragraph in the middle of parent div regardless of parent divs size
I am having a real difficulty. I have a number of images with a caption on top of the image.
I am trying to center the caption horizontally and vertically regardless of the size of the image
开发者_运维问答I presume it would be a little bit of clever Jquery but I can't seem to find anything out there.
Below is the url for the page
http://satbulsara.com/luke-irwin/?page_id=175
Thanks,
Sat
The easiest thing to do is to add a left
and width
property to contain the text. However, this does make the assumption that the text is limited in length.
#rugs #content .rugsAll div p {
color: #FFFFFF;
font-size: 24px;
left: 35%;
position: absolute;
text-align: center;
z-index: 4;
top: 40%;
width: 20%;
}
If you have varying length captions. Then you will need jQuery to dynamically set the left
and top
property to center it based on the image size.
sat,
If you make the width of your <p>
class 100% then the text-align:center
will place your text in the center horizontally.
Vertical alignment is trickier. You should probably wrap your <p>
in a container and vertical-align:middle
that container.
CSS:
.container {
width: 100%;
vertical-align:middle;
}
p .wp-caption-text {
position: relative;
display: block;
z-index: 40;
font-size: 24px;
text-align: center;
width: 100%;
color: #fff;
}
HTML
<div id="attachment_249" class="wp-caption alignnone" style="width: 319px">
<img class="animal new" title="Rug-12" src="http://satbulsara.com/luke-irwin/wp-content/uploads/2011/05/Rug-121.jpg" alt="" width="309" height="453" />
<div class="container">
<p class="wp-caption-text">
testing 8
</p>
</div>
</div>
I believe something like this will work. Play around with it, but I think it'll do.
I used this solution
$('.wp-caption-text').each(function() {
this.style.position = 'absolute';
this.style.top = $(this).parent().height()/2 + 'px';
this.style.marginTop = -$(this).height()/2 + 'px';
this.style.left = ($(this).parent().width() - $(this).width())/2 + 'px';
});
精彩评论