DIV盒子实现水平垂直居中的方法
记录下学习css的进程,记录一下遇到的难点。
绝对定位下DIV
盒子的位置
-
垂直水平都居中
方法一:
css样式
- .test1 {
- position:fixed;
- width:200px;
- height:100px;
- background-color:red;
- left:50%;
- top:50%;
- margin-left:-100px;/*width宽度的一半*/
- margin-top:-50px;/*height宽度的一半*/
- }
实现的效果:垂直水平都居中如下图
方法2:
css样式:
- .test2 {
- position:fixed;
- width:200px;
- height:100px;
- background-color:red;
- left:0;
- right:0;
- top:0;
- bottom:0;
- margin:auto auto;
- }
实现的效果:垂直水平都居中如下图
-
水平或垂直方向上的居中
以上两种方法第一种只设置水平的left
和margin-left
属性即可实现水平居中,只设置top
和margin-top
属性即可实现垂直居中;第二种水平居中只需设置left:0
、right:0
、margin:0 auto
即可实现,垂直居中只需设置top:0
、bottom:0
、margin:auto 0
即可实现。
子DIV在父DIV中的居中
子DIV位置为默认值时的定位:即position:static,或者position:relative时
水平居中的子div css样式
- /*css样式*/
- .test1 {
- position:fixed;
- width:400px;
- height:200px;
- background-color:red;
- left:50%;
- top:50%;
- margin-left:-200px;/*width宽度的一半*/
- margin-top:-100px;/*height宽度的一半*/
- text-align:center;
- }
- .test2 {
- position:static;
- width:200px;
- height:100px;
- background-color:burlywood;
- border:1px solid #000;
- text-align:right;
- margin:0 auto;
- }
- /*html内容*/
- <div class="test1">我在中间<div class="test2">我在右边</div></div>
效果如下图所示,text-align
规定了div中文本元素的对齐方式,子div只需设置外边距margin:0 auto
就能实现水平居中,
子DIV位置为absolute时,即position:absolute,可以使用left、right、top、bottom相对于父DIV定位(父DIV位置必需是fixed、absolute、relative其中一种)
水平居中css
- .test1 {
- position:relative;
- width:400px;
- height:200px;
- background-color:red;
- text-align:center;
- }
- .test2 {
- position:absolute;
- width:200px;
- height:100px;
- background-color:burlywood;
- border:1px solid #000;
- text-align:rightright;
- left:0;
- rightright:0;
- margin:0 auto;
- }
- 或者
- .test2 {
- position:absolute;
- width:200px;
- height:100px;
- background-color:burlywood;
- border:1px solid #000;
- text-align:right;
- left:50%;
- margin-left:-100px;/*width宽度的一半*/
- }
实现的效果如下图
发表评论
要发表评论,您必须先登录。