首页 > Web开发 > 详细

css未知宽高的盒子div居中的多种方法

时间:2017-02-04 20:00:16      阅读:329      评论:0      收藏:0      [点我收藏+]

  不知道盒子大小、宽高时,如何让盒子上下左右居中?

  应用场景:比如上传图片时,并不知道图片的大小,但要求图片显示在某盒子的正中央。

方法1:让4周的拉力均匀-常用

<!--
Author: XiaoWen
Create a file: 2017-01-13 13:46:47
Last modified: 2017-01-13 14:05:04
Start to work:
Finish the work:
Other information:
-->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    *{
      margin:0;
      padding:0;
    }
    #box1{
      width: 100px;
      height: 100px;
      background: #ccc;
      position:relative;
    }
    #box2{
      width: 20px;
      height: 20px;
      background: #f00;
      position:absolute;
      top:0; /* 四周拉力相同 */
      right:0; /* 四周拉力相同 */
      bottom:0; /* 四周拉力相同 */
      left:0; /* 四周拉力相同 */
      margin:auto; /* 再设置 marign 自动 */
    }

  </style>
</head>
<body>
  <div id="box1">
    <div id="box2"></div>
  </div>
</body>
</html>

方法2:c3的属性,移动自己大小的一半

<!--
Author: XiaoWen
Create a file: 2017-01-13 13:46:47
Last modified: 2017-01-13 14:07:09
Start to work:
Finish the work:
Other information:
-->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    *{
      margin:0;
      padding:0;
    }
    #box1{
      width: 100px;
      height: 100px;
      background: #ccc;
      position:relative;
    }
    #box2{
      width: 20px;
      height: 20px;
      background: #f00;
      position:absolute;
      top:50%;
      left:50%;
      transform:translate(-50%,-50%);
    }

  </style>
</head>
<body>
  <div id="box1">
    <div id="box2"></div>
  </div>
</body>
</html>

知道自身高度的情况下,使用负边距,-margin自身高度的一半

<!--
Author: XiaoWen
Create a file: 2017-01-13 13:46:47
Last modified: 2017-01-13 14:02:45
Start to work:
Finish the work:
Other information:
-->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    *{
      margin:0;
      padding:0;
    }
    #box1{
      width: 100px;
      height: 100px;
      background: #ccc;
      position:relative;
    }
    #box2{
      width: 20px;
      height: 20px;
      background: #f00;
      position:absolute;
      left:50%;
      top:50%;
      margin-left:-10px; /* 知道自己大小的情况,自身高度的一半 */
      margin-top:-10px; /* 知道自己大小的情况,自身高度的一半 */
    }

  </style>
</head>
<body>
  <div id="box1">
    <div id="box2"></div>
  </div>
</body>
</html>

 

css未知宽高的盒子div居中的多种方法

原文:http://www.cnblogs.com/daysme/p/6366089.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!