1. div高度自适应的状况css
div在不设置高度的时候,会被里面的内容撑开,内容自动填充在div中,不管是一行内容仍是多行内容,此时不须要设置垂直居中,内容自动在中间的,css3
想要看的更直观些,只须要加上padding元素,内容四周便会留下空白,实现水平垂直居中的效果web
css代码以下:浏览器
.demo{ width: 200px; border: 1px solid red; padding: 20px; }
HTML代码以下:布局
<div class="demo"> this is a test of margin this is a test of margin this is a test of margin this is a test of margin this is a test of margin </div>
效果以下所示:flex
2.div设置具体高度this
(1)内容只有一行spa
设置div的line-height和div的高度同样便可,这个你们都知道哒code
(2)内容不肯定有几行orm
这时候须要在div中再加一层结构,用p标签或者div均可以
方法一:
css代码以下:
.demo{ position: absolute; width: 200px; height: 200px; border: 1px solid red; } p{ position: absolute; width: 150px; top: 50%; left:50%; transform: translate(-50%,-50%); border: 1px solid black; }
HTML代码以下:
<div class="demo"> <p> this is a test of margin this is a test of margin this is a test of margin this is a test of margin </p> </div>
效果以下:
方法二:如果不想用position:absolute这样的脱离文档流的样式,那就能够尝试模拟表格的方法
设置父元素display:table,设置子元素display:table-cell,并设置vertical-align:middle便可
css代码以下:
.demo{ width: 200px; height: 200px; display: table; border: 1px solid red; } p{ display: table-cell; vertical-align: middle; text-align: center; border: 1px solid black; }
HTML代码以下:
<div class="demo"> <p> this is a test of margin this is a test of margin this is a test of margin this is a test of margin </p> </div>
效果以下所示:
此时子元素设置宽度是没用的,宽度始终和父元素一致;
可是若是子元素设置高度的话,如果高度小于父元素则无效果,如果高度大于父元素则父元素的高度也相应增长到和子元素同样的高度
方法三:
使用css3新增的flex布局完成。
设置父元素display:box; box-pack:center; box-orient:vertical;便可,记得要在前面加上浏览器前缀哦
css代码以下:
.box{ width: 200px; height: 200px; border: 1px solid red; display: box; box-pack:center; box-orient:vertical; display: -webkit-box; -webkit-box-pack:center; -webkit-box-orient:vertical; }
HTML代码以下:
<div class="box"> <div> this is a test this is a test this is a test </div> <div> this is another test for the second div </div> </div>
效果显示以下:
(by新手小白的记录)