标签:情况 移动 relative ast utf-8 上传 上传图片 div 图片显示
不知道盒子大小、宽高时,如何让盒子上下左右居中?
应用场景:比如上传图片时,并不知道图片的大小,但要求图片显示在某盒子的正中央。
<!-- 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>
<!-- 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>
<!-- 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>
标签:情况 移动 relative ast utf-8 上传 上传图片 div 图片显示
原文地址:http://www.cnblogs.com/daysme/p/6366089.html