zoukankan      html  css  js  c++  java
  • jquery实现水平垂直居中

    在建立网页布局的时候,我们经常会面临一个问题,就是让一个div实现水平和垂直居中,虽然好几种方式实现,但是今天介绍时我最喜欢的方法,通过css和jQuery实现。
    1、通过css实现水平居中:
    .className{
     margin
    :0 auto;
     width
    :200px;
     height
    :200px;
    }

    2、通过css实现水平居中和垂直居中

    通过css创建一个水平居中和垂直居中的div是一件比较麻烦的事情,您必须事先知道另外一个div的尺寸:

    复制代码
    .className{
     width
    :300px;
     height
    :200px;
     position
    :absolute;
     left
    :50%;
     top
    :50%;
     margin
    :-100px 0 0 -150px;
    }
    复制代码

    3、通过jQuery实现水平居中和垂直居中前面已经提到过了,css的方法只适用于有固定尺寸的div,所以到jQuery发挥作用了:

    复制代码
    $(window).resize(function(){
     $(
    '.className').css({
      position:
    'absolute',
      left: ($(window).width() 
    - $('.className').outerWidth())/2,
       top: ($(window).height() - $('.className').outerHeight())/2 + $(document).scrollTop()
     });
    });
    //初始化函数
    $(window).resize();
    复制代码

    这种方法的好处是您无需知道div有多大,缺点是它只能通过JavaScript实现。

  • 相关阅读:
    nyoj 202红黑树 (搜索)
    POJ 3281 Dining(最大流)
    nyoj-488 素数环 +nyoj -32 组合数 (搜索)
    LeetCode100:Same Tree
    LeetCode283:Move Zeros
    Leetcode226:Invert Binary Tree
    LeetCode258:Add Digits
    Leetcode237:Delete Node in a Linked List
    LeetCode7:Reverse Integer
    LeetCode292:Nim Game
  • 原文地址:https://www.cnblogs.com/zzcflying/p/2547575.html
Copyright © 2011-2022 走看看