企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
**等式:** `left + margin-left + border-left +padding-left +width + padding-right + border-right + margin-right + right (9个值)= 包含块的内容的宽度 ` 当我们开启了绝对定位后: 水平方向的布局等式就需要多添加left和right两个值 ## ## **当发生过度约束:** **1、如果9个值中没有auto则自动调整right值以使等式满足** 例子1、包含块的内容的宽度 =0+100+0===500,显然0+100+0是凑不齐500的,这就是过度约束,那么right:0;这个设置是无效的,浏览器会自动调整right的值为400 ``` <!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="utf-8"> <title>site title</title> <style type="text/css"> .box1{ width: 500px; height: 500px; background-color: #bfa; position: relative; } .box2{ width: 100px; height: 100px; background-color: #fba; position: absolute; left:0; right: 0; } </style> </head> <body> <div class="box1"> <div class="box2"></div> </div> </body> </html> ``` ![](https://img.kancloud.cn/d4/36/d436799301af2783c7564c93928b16eb_608x421.png) **2、如果有auto,则自动调整auto的值以使等式满足** 可设置auto的值:margin width left right 例子2、与例子1一样过度约束,当with设置了auto则自动调整width的值为500,即0+500+0=500 ``` <!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="utf-8"> <title>site title</title> <style type="text/css"> .box1{ width: 500px; height: 500px; background-color: #bfa; position: relative; } .box2{ width: auto; height: 100px; background-color: #fba; position: absolute; left:0; right: 0; } </style> </head> <body> <div class="box1"> <div class="box2"></div> </div> </body> </html> ``` ![](https://img.kancloud.cn/30/e6/30e6fd3c1ed59a1c106dd82772d3936f_793x486.png) 例子3、与例子2一样过度约束,当margin设置了auto则自动调整margin的值,即0+200+100+200+0=500 ``` <!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="utf-8"> <title>site title</title> <style type="text/css"> .box1{ width: 500px; height: 500px; background-color: #bfa; position: relative; } .box2{ width: 100px; height: 100px; background-color: #fba; position: absolute; margin-left: auto; margin-right: auto; left:0; right: 0; } </style> </head> <body> <div class="box1"> <div class="box2"></div> </div> </body> </html> ``` ![](https://img.kancloud.cn/bb/04/bb04c6a3ab46b6864297dbcd6dc3598e_532x368.png) left与right的默认值是auto,所以不设置left与right时即left与right不确定时,会自动调整left与right的值,此时margin width的auto值是不生效的 ``` <!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="utf-8"> <title>site title</title> <style type="text/css"> .box1{ width: 500px; height: 500px; background-color: #bfa; position: relative; } .box2{ width: 100px; height: 100px; background-color: #fba; position: absolute; margin-left: auto; margin-right: auto; left:auto; right: auto; } </style> </head> <body> <div class="box1"> <div class="box2"></div> </div> </body> </html> ``` ![](https://img.kancloud.cn/5b/a6/5ba6897bb1dfcb0f111fa53dc8f7704f_466x445.png)