jQuery vertical align middle 移动整个 div

标签 jquery html css vertical-alignment

当使用 jQuery 垂直对齐 div 中的文本时,整个 div 都会移动。文本与其他 div 垂直对齐,但仍与它所在的 div 顶部对齐。我怎样才能阻止它这样做?

这是一个 jsfiddle:http://jsfiddle.net/gvwzdjas/

遗憾的是, fiddle 并没有准确显示正在发生的事情。我不确定用另一种方式来展示它...

这是我正在使用的 HTML。

         <div class="grid grid-pad">
            <div class="col-1-3">
                <div class="content">
                  <h3>
                     TEXT HERE
                  </h3>
                </div>
            </div>
            <div class="col-1-3">
                <div class="content">
                    <h3>
                      TEXT HERE
                    </h3>
                </div>
            </div>
            <div class="col-1-3">
                <div class="content">
                    <h3>
                      TEXT HERE
                    </h3>
                </div>
            </div>
        </div>

这是我正在使用的 jQuery。

<script>
  (function ($) {
    // VERTICALLY ALIGN FUNCTION
    $.fn.vAlign = function() {
      return this.each(function(i){
        var ah = $(this).height();
        var ph = $(this).parent().height();
        var mh = Math.ceil((ph-ah) / 2);
        $(this).css('margin-top', mh);
      });
    };
  })(jQuery);
  $('#item').vAlign();
</script>

这是我正在使用的 CSS

*, *:after, *:before {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}

[class*='col-'] {
float: left;
padding-right: 20px; /* column-space */
}

.grid {
width: 100%;
max-width: 1140px;
min-width: 755px;
margin: 0 auto;
overflow: hidden;
}

.grid:after {
content: "";
display: table;
clear: both;
}

.grid-pad {
padding-top: 10px;
padding-left: 20px; /* grid-space to left */
padding-right: 0px; /* grid-space to right: (grid-space-left - column-space) e.g. 20px-20px=0 */
}

.col-1-3, .col-4-12 {
width: 33.33%;
}

.content {
height:250px;
background-color:#fff;
text-align:center;
}

最佳答案

$('#item').vAlign(); 您的 html 中没有 #item

尝试

h3{
    position: relative;
}

(function ($) {
          // VERTICALLY ALIGN FUNCTION
          $.fn.vAlign = function () {
              return this.each(function (i) {
                  var ah = $(this).height();
                  var ph = $(this).parent().height();
                  var mh = Math.ceil((ph - ah) / 2);
                  $(this).css('top', mh);
              });
          };
      })(jQuery);
      $('h3').vAlign();

看看jsfiddle

关于jQuery vertical align middle 移动整个 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26196190/

相关文章:

javascript - 使用 JavaScript 在 XML 中查找 ID

javascript - 刷新 div 后 CSS 样式不起作用

php - 使用远程图像和样式表将 PHP HTML 内容转换为 DOC/PDF

html - 为什么 Navbar Collapse 按钮​​总是显示在我的网页上?

javascript - 如何在保留 span 标记的同时在 contenteditable div 中的 pre-span-wrap 文本中键入和删除文本

jquery - 具有不在列表中的默认值的下拉列表选项

javascript - 关闭时从 Bootstrap 模式中清除数据属性值

Python 循环和网页抓取 |美汤

javascript - 谷歌地图的宽度和高度

javascript - Bootstrap 模态样式表单验证