子元素在父元素中垂直居中
方法一:
要求水平和垂直居中,可以是用margin:0 auto;和marggin-top:(父元素-子元素)/2
方法二:
要求子元素垂直居中,水平更加设计布局,可以使用定位,父元素relative,子元素absolute,并且子元素top设置50%,margin-top设置为子元素高的一半的负值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | !DOCTYPE html> < html > < head > < meta charset="utf-8" /> < title >让DIV标签中的P标签水平和垂直都居中</ title > < style type="text/css"> div { position: relative; width:400px; height:300px; overflow:hidden; background-color: #0cbb08; } p { position: absolute; top: 50%; margin-top: -25px; border:1px solid #333; width:200px; height: 50px; border-radius: 25px; background-color: #ff9236; line-height: 50px; text-align: center; } * { margin:0; padding:0;} </ style > </ head > < body > < div > < p >我要水平和垂直都居中</ p > </ div > </ body > </ html > |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步