企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## 居中 **示例链接:** http://www.lsxm.tech/doc/demo/center.html >[success]### 一、水平居中 #### 1、块状元素水平居中 **width: 150px; margin:0 auto;** <div style="width: 150px;margin:0 auto;background:red">margin:0 auto;</div> 即通过左右外边距自动(auto)来实现水平居中. (需要设置宽度) #### 2、内联元素水平居中 **text-align:center;** 设置父div为text-align:center;让div里的块状元素水平居中 <div style="text-align:center;background:red"><span>text-align:center;</span></div> #### 3、定位水平居中 **position: absolute; left:50%; width: 100px; margin-left:-50px;宽度的一半** 通过绝对定位(fixed也行),设置left为:50%;最后向左偏移宽度的一半来抵消div以左边框定位所产生的偏移。 <div style="position:relative;height:200px;background:green"> <div style="position:absolute;left:50%;top:0;width:200px;margin-left:-100px;background:red"> position: absolute;<br> left:50%;<br> width: 100px;<br> margin-left:-50px; </div> </div> >[info]### 二、垂直居中 #### 1、内联元素垂直居中line-height=height **height: 100px; line-height: 100px;** <div style="height:100px;line-height:100px;background:red"> margin:0 auto; </div> #### 2、定位垂直居中 **position: absolute; top:50%; height: 100px; margin-top:-50px;高度的一半** <div style="position:relative;height:200px;background:green"> <div style="position:absolute;left:50%;top:50%;width:200px;height:120px;margin-left:-100px;margin-top:-60px;text-align:center;background:red"> position: absolute;<br> top:50%;<br> width: 100px;<br> margin-top:-50px; </div> </div> #### 3 、js计算居中 绝对定位,用js计算left、top。如 left:(父width-子width)/2 top:(父height-父height)/2 通常用于父子元素高度、宽度不确定或产生变动的情况下。