5种实现垂直居中的方法

您所在的位置:网站首页 div中文字垂直居中的方法 5种实现垂直居中的方法

5种实现垂直居中的方法

2022-11-19 04:08| 来源: 网络整理| 查看: 265

1、使用table的自带功能:通过table标签,下面放个tr,里面用td包裹内容,不管table设不设置高度,内容多会垂直居中。

JS Bin 一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字 css: .parent{ border: 1px solid red; height: 600px;//设置了高度,内容会垂直居中,不设高度,table就会被内容撑高。 } .child{ border: 1px solid green; }

2、使用绝对定位+margin-top:-50%

JS Bin 一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字 css: .parent{ height: 600px; border: 1px solid red; position: relative; } .child{ border: 1px solid green; width: 300px; position: absolute; top: 50%; left: 50%; margin-left: -150px; height: 100px; margin-top: -50px; }

3、使用绝对定位+transform: translate(-50%,-50%);

JS Bin 一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字 css: .parent{ height: 600px; border: 1px solid red; position: relative; } .child{ border: 1px solid green; position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); }

4、使用绝对定位+ margin auto

JS Bin 一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字 css: .parent{ height: 600px; border: 1px solid red; position: relative; } .child{ border: 1px solid green; position: absolute; width: 300px; height: 200px; margin: auto; top: 0; bottom: 0; left: 0; right: 0; }

5、flex

JS Bin 一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字 css: .parent{ height: 600px; border: 3px solid red; display: flex; justify-content: center; align-items: center; } .child{ border: 3px solid green; width: 300px; }



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3