HTML/CSS:div居中和div内部元素垂直居中
div居中
div水平和垂直居中,text-align和vertical-align不起作用,因为标签div没有这两个属性,所以再css中设置这两个值不能居中的效果
1. div水平居中:设置margin的左右边距为自动
div { margin:0 auto; }
6种元素垂直居中的方法
利用CSS进行元素的水平居中,比较简单,行级元素设置其父元素的text-align center,块级元素设置其本身的left 和 right margins为auto即可。本文收集了六种利用css进行元素的垂直居中的方法,每一种适用于不同的情况,在实际的使用过程中选择某一种方法即可。
1.Line-Height Method
适用:单行文本垂直居中
代码:
html
<div id="parent"> <div id="child">Text here</div> </div>
css
#child { line-height: 200px; }
垂直居中一张图片,代码如下
html
<div id="parent"> <img src="image.png" alt="" /> </div>
css
#parent { line-height: 200px; } #parent img { vertical-align: middle; }
2.CSS Table Method
适用:通用
代码:
html
<div id="parent"> <div id="child">Content here</div> </div>
css
#parent {display: table;} #child { display: table-cell; vertical-align: middle; }
低版本 IE fix bug:
#child { display: inline-block; }
3.Absolute Positioning and Negative Margin
适用:块级元素
代码:
html
<div id="parent"> <div id="child">Content here</div> </div>
css
#parent {position: relative;} #child { position: absolute; top: 50%; left: 50%; height: 30%; width: 50%; margin: -15% 0 0 -25%; }
4.Absolute Positioning and Stretching
适用:通用,但在IE版本低于7时不能正常工作
代码:
html
<div id="parent"> <div id="child">Content here</div> </div>
css
#parent {position: relative;} #child { position: absolute; top: 0; bottom: 0; left: 0; right: 0; width: 50%; height: 30%; margin: auto; }
5.Equal Top and Bottom Padding
适用:通用
代码:
html
<div id="parent"> <div id="child">Content here</div> </div>
css
#parent { padding: 5% 0; } #child { padding: 10% 0; }
6.Floater Div
适用:通用
代码:
html
<div id="parent"> <div id="floater"></div> <div id="child">Content here</div> </div>
css
#parent {height: 250px;} #floater { float: left; height: 50%; width: 100%; margin-bottom: -50px; } #child { clear: both; height: 100px; }
以上就是六种方法,可以在实际的使用过程中合理选择,参考文章《vertical-centering》
原文链接:http://blog.zhourunsheng.com/2012/03/css-%E5%85%83%E7%B4%A0%E5%9E%82%E7%9B%B4%E5%B1%85%E4%B8%AD%E7%9A%84-6%E7%A7%8D%E6%96%B9%E6%B3%95/
(资源库 www.zyku.net)
上一篇:HTML中meta的作用
栏 目:HTML/Xhtml
下一篇:html中实现数据的显示和隐藏
本文标题:HTML/CSS:div居中和div内部元素垂直居中
本文地址:https://www.zyku.net/xhtml/1402.html
您可能感兴趣的文章
- 07-04JS点击缩略图整屏居中放大图片效果
- 11-03QQ浏览器怎么添加直达网站
- 12-23HTML <colgroup> 标签
- 02-17ASP.NET MVC分页控件
- 10-23vivox70pro+如何设置自动开关机
- 02-21Linux中删除文件功能详解
- 10-04boss直聘实名认证如何解除
- 03-01荣耀畅玩20三指导航设置教程
- 12-31小学语文课堂笔记-小学语文课堂笔记应
- 04-06一加9pro添加桌面插件方法
- 07-04华为手机隐藏录音通知步骤
- 02-10详解MySQL中InnoDB的存储文件
- 09-13oppo免打扰允许来电名单在哪设置
- 07-05Linux mount命令
- 08-10微信健康码如何解除绑定?
- 12-13iPhone6sPlus高德车道级导航在哪开
- 10-19钉钉在哪查询企业信息
- 09-20QQ看点在哪里查看等级
- 06-18帝国CMS7.5版新增会员访问组,控制会员
- 08-10利用PHP生成随机密码的几种方法
最近更新
阅读排行
猜你喜欢
- 03-13帝国CMS判断会员是否登录及登录后才能
- 09-19苹果手机怎样添加公交卡
- 09-19iqoo8微云台校准使用方法分享
- 10-30百度蜘蛛抓取耗时长解决方法
- 02-18html5 div布局与table布局详解
- 11-29美图秀秀怎么关闭私信
- 11-03goodnotes滚动方向调整教程分享
- 12-28苹果手机查看序列号方法分享
- 09-20荣耀手机如何设置桌面天气小组件
- 12-28手机录音精灵-手机录音精灵应用软件功