div中内容水平垂直居中
2017-10-20 15:45
176 查看
1. div高度自适应的情况
div在不设置高度的时候,会被里面的内容撑开,内容自动填充在div中,无论是一行内容还是多行内容,此时不需要设置垂直居中,内容自动在中间的,
想要看的更直观些,只需要加上padding元素,内容四周便会留下空白,实现水平垂直居中的效果
css代码如下:
HTML代码如下:
效果如下所示:
2.div设置具体高度
(1)内容只有一行
设置div的line-height和div的高度一样即可,这个大家都知道哒
(2)内容不确定有几行
这时候需要在div中再加一层结构,用p标签或者div都可以
方法一:
css代码如下:
HTML代码如下:
效果如下:
方法二:若是不想用position:absolute这样的脱离文档流的样式,那就可以尝试模拟表格的方法
设置父元素display:table,设置子元素display:table-cell,并设置vertical-align:middle即可
css代码如下:
HTML代码如下:
效果如下所示:
此时子元素设置宽度是没用的,宽度始终和父元素一致;
但是如果子元素设置高度的话,若是高度小于父元素则无效果,若是高度大于父元素则父元素的高度也相应增加到和子元素一样的高度
方法三:
使用css3新增的flex布局完成。
设置父元素display:box; box-pack:center; box-orient:vertical;即可,记得要在前面加上浏览器前缀哦
css代码如下:
9786
HTML代码如下:
效果显示如下:
div在不设置高度的时候,会被里面的内容撑开,内容自动填充在div中,无论是一行内容还是多行内容,此时不需要设置垂直居中,内容自动在中间的,
想要看的更直观些,只需要加上padding元素,内容四周便会留下空白,实现水平垂直居中的效果
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>
效果如下所示:
2.div设置具体高度
(1)内容只有一行
设置div的line-height和div的高度一样即可,这个大家都知道哒
(2)内容不确定有几行
这时候需要在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; }
9786
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>
效果显示如下:
相关文章推荐
- css+div设置内容水平和垂直居中
- css div内容水平,垂直居中限制
- div里的内容水平居中和垂直居中
- div内容水平居中、垂直居中
- HTML中一个div中关于其内容的水平和垂直居中
- 实现 div 里面的内容div水平且垂直居中
- h5中设置div中的内容水平并垂直居中
- 让div水平垂直居中
- div水平垂直居中的方法
- 如何让div中的内容垂直居中
- css实现div的水平和垂直居中
- div中的内容垂直居中的五种方法
- CSS相邻选择器(>)选择子元素而不包含该子元素的子元素,及如何让DIV中的内容垂直居中
- DIV水平垂直居中的CSS兼容写法
- div自动适应浏览器窗口水平和垂直居中
- div盒子水平垂直居中方法
- div水平垂直居中
- css+div水平垂直居中布局总结(3种方案)
- css实现div内图片的垂直、水平居中
- jquery计算出left和top,让一个div水平垂直居中的简单实例