如何居中一个float:left的元素

第一种方法

<style type="text/css"> .box { float: left; width: 100px; height: 100px; background: lightcoral; } </style> <body> <div class="box"></div> </body>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

现在它所处的位置 在页面的最左边 
这里写图片描述

我们都知道在浮动的情况下添加margin: 0 auto; 是没有任何效果的。

那么我们在box的外面再套一个div 就是给他一个爸爸 让他的爸爸处于页面的正中央

<style type="text/css"> .con { position: relative; float: left; left: 50%; background: lightblue; } .box { position: relative; float: left; left: -50%; width: 100px; height: 100px; background: lightcoral; } </style> <body> <div class="con"> <div class="box"></div> </div> </body>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

运行代码 我们得到下面的结果

这里写图片描述

蓝色的con为砖红色box的“爸爸”,从图上我们可以很清楚的看到, con通过定位往左移了百分之五十。而box通过相对定位,定位在con的-50%的地方,即为正中心。

给子元素相对定位,是想将相对于父元素来定位自己的位置,float:left让子元素在同一水平线上显示,left:-50%是因为子元素的整体宽度就是父元素的宽度,left:50%就是让子元素内容往相对父元素左上那一点往左移动父元素一半的宽度(right:50%是距右边50%,效果一样),正好实现子元素内容居中显示的效果。

这是引用了别人的话,会更加清晰。

第二种方法

是使用原生JavaScript写的

<body>
    <div id="con" class="box"></div> <script type="text/javascript"> var con = document.getElementById('con'); con.style.position = 'relative'; con.style.left = (document.body.offsetWidth - con.clientWidth) / 2 + 'px'; </script> </body>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

通过获取屏幕的总宽度 减去box本身的宽度 除以二 便得到了中心的位置。

第三种方法

JQ

<body>
    <div class="box"></div> <script type="text/javascript" src="../js/jquery-1.12.3.js"></script> <script type="text/javascript"> $('.box').css({ 'position' : 'relative', 'left' : ($(window).width() - $('.box').outerWidth()) / 2 + 'px' }) </script> </body>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

和JS的原则是一样的~

猜你喜欢

转载自www.cnblogs.com/kissyanyu/p/9650314.html