垂直对齐各种div中间的文本

时间:2011-05-12 17:29:43

标签: jquery

嗨我在不同大小的div中的图像下面有一些文本,文本已经水平居中但我想使用jquery垂直和水平居中这个文本。

我该怎么做?

下面是示例页面

http://satbulsara.com/luke-irwin/?page_id=175

谢谢,

周六

2 个答案:

答案 0 :(得分:1)

这里有一个例子,如何垂直居中:http://jsfiddle.net/9Aqd8/

<div style="height:120px; width:120px; border: 1px solid black">
    <div class="textToAlign" style="text-align:center; width:100%">Text</div>
<div>

$(function() {
    $('.textToAlign').each( function( index, item) {
         var parent = $(item).parent();
         var $this = $(item);
         parent.css('position', 'relative');
         $this.css('position', 'absolute').css('top', Math.round((parent.height() - $this.outerHeight()) / 2) + 'px');
    });
});

答案 1 :(得分:0)

CSS解决方案:
http://matthewjamestaylor.com/blog/equal-height-columns-cross-browser-css-no-hacks

JQuery解决方案:

一个。将所有框的HTML结构更改为:

<div class="wp-caption alignnone">
  <div class="imageContainer">
    <img class="new geometric ikat" title="Rug-3" src="http://satbulsara.com/luke-irwin/wp-content/uploads/2011/05/Rug-31.jpg" alt="" width="308" height="409" />
  </div>
  <p class="wp-caption-text">Testing 4</p>
</div>

湾JQuery代码:

var maxHt = 0;
var $containers = $('div.imageContainer');
$containers.each(function(){
  var ht = $(this).height();
  if (ht > maxHt) {
    maxHt = ht;
  }
});
$containers.height(maxHt);