其他分享
首页 > 其他分享> > 元素在其父元素垂直水平都居中的方法

元素在其父元素垂直水平都居中的方法

作者:互联网

元素在其父元素的垂直和水平方向都居中的方法

话不多说直接上代码

html代码统一如下:

复制到你的***.html目录下的<body></body>标签里面

<div class="wrap">
	<div class="inner">
	
	</div>
</div>

以下为CSS代码:

复制到你的***.html目录下的<head><style></style></head>里面,或者引入外部样式表,将此代码放到你的***.css文件里,
注意:link标签的href指定的文件位置不要搞错了哦。

  1. 定位方法(1)
.wrap{
	width: 300px;
    height: 300px;
    background: yellow;/*加颜色是为了看界面效果*/
    position: relative;
}
.inner{
  	width: 40px;
   	height: 40px;
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin:auto;
    background: orange;/*加颜色是为了看界面效果*/
 }
  1. 定位方法(2)
    .wrap{
        width: 300px;
        height: 300px;
        position: relative;
        background: yellow;/*加颜色是为了看界面效果*/
    }
    .inner{
        width: 40px;
        height: 40px;
        position: absolute;
        left: 50%;
        top: 50%;
        margin-left:-20px;
        margin-top: -20px;
        background: orange;/*加颜色是为了看界面效果*/
    }
    
  2. 改变父元素和子元素的display(不推荐使用)
	.wrap{
        width: 300px;
        height: 300px;
        display: table-cell;
        text-align: center;
        vertical-align: middle;
        background: yellow;/*加颜色是为了看界面效果*/
    }
    .inner{
        width: 40px;
        height: 40px;
        display: inline-block;
        background: orange;/*加颜色是为了看界面效果*/
    }
  1. css3的弹性盒方法
	.wrap{
        width: 300px;
        height: 300px;
        display: flex;
        justify-content: center;
        align-items: center;
        background: yellow;
    }
    .inner{
        width: 40px;
        height: 40px;
        background: orange;
    }

但是display:flex属性小伙伴们要注意一下它的兼容问题哦~图片上标红的版本的浏览器就是不支持该属性的哦。
在这里插入图片描述
以上四种方法在浏览器上实现的效果图如下:
在这里插入图片描述

如果小伙伴们还知道什么其他的方法欢迎给笔者留言评论哦~笔者感激不尽,也能帮助其他看笔者博客的朋友们。谢谢大家!

标签:居中,40px,其父,元素,300px,height,width,background,display
来源: https://blog.51cto.com/u_15275953/2928468