css实现div垂直水平居中

来源:互联网 发布:李洪成排盘软件下载 编辑:程序博客网 时间:2024/05/22 09:41

方法一:display:table-cell 实现

<div class="wrapper"><div class="content">content</div></div>
div居中:对父元素用display: table-cell; 子元素用display: inline-block;

文字居中:将line-height设为容器高度。

<style type="text/css">.wrapper{width: 300px;height: 200px;background: blue;display: table-cell;text-align: center;vertical-align: middle;}.content{width: 150px;height: 80px;line-height: 80px;background: red;display: inline-block;}</style>

方法二:position: absolute 实现

<style type="text/css">.wrapper{width: 300px;height: 200px;background: blue;position: relative;}.content{width: 150px;height: 80px;line-height: 80px;background: red;text-align: center;position: absolute;margin: auto;top: 0;left: 0;bottom: 0;right: 0;}</style>


方法三:弹性盒布局实现

可实现一个或多个内容块垂直水平居中

<div class="wrapper"><div class="content content1">content1</div><div class="content content2">content2</div><div class="content content3">content3</div></div>

按列分布的多个div的垂直水平居中
<style type="text/css">.wrapper{width: 300px;height: 200px;background: blue;display: flex;flex-direction:column;justify-content:center;align-items:center;}.content{width: 150px;height: 20px;line-height: 20px;background: red;text-align: center;margin: 5px;}</style>

按行分布的多个div的垂直水平居中
<style type="text/css">.wrapper{width: 300px;height: 200px;background: blue;display: flex;flex-direction:row;justify-content:center;align-items:center;}.content{width: 20px;height: 150px;line-height: 20px;background: red;text-align: center;writing-mode: tb-rl;margin: 5px;}</style>