簡體   English   中英

jQuery垂直對齊中間移動整個div

[英]jQuery vertical align middle moves entire div

當使用jQuery在div中垂直對齊文本時,整個div都會移動。 文本與其他div垂直對齊,但仍在其所在的div頂部對齊。如何阻止它呢?

這是一個jsfiddle: http : //jsfiddle.net/gvwzdjas/

可悲的是,小提琴並沒有完全顯示正在發生的事情。 我不確定另一種顯示方式...

這是我正在使用的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;
}

僅在CSS中使用不設置jquery的情況

  .content {
height:250px;
position:relative;
background-color:#fff;
text-align:center;
}
.content h3{
position:absolute;
top:50%;
left:50%;
}

或者在jquery選項css中設置此樣式

您可以使用css中的flex屬性垂直對齊內容,而不是使用腳本。

演示

CSS:

.content {
    display: flex;
    justify-content: center;        /* align horizontal */
    align-items: center;        /*ALIGN VERTICAL*/
    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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM