您的位置:首页 > Web前端 > CSS

html + css 居中方法大全

2017-11-17 16:21 197 查看
css居中

水平居中:

说到水平居中,最简单的方法就是
margin:0 auto;


也就是将margin-left 和 margin-right属性设置为auto;

源码和效果如下图所示:





ps:不要想当然的以为简单地将margin值设置为auto,就可以将元素水平、垂直居中(不过在css3弹性布局中确实可以这样子做,这里暂不做过多讨论);

文本的居中对齐方式:





ps:文本垂直对齐一般上设置line-height和height 相等的值就可以!

padding填充

利用paddingbackground-clip配合实现div的水平垂直居中:

通过backgroun-clip设置为content-box,将背景裁剪到内容区外沿,再利用padding设为外div减去内div的差的一半,来实现:





盒子模型



绝对定位居中






4000
模型







盒模型



调整尺寸

resize 属性可以让尺寸可调。 设置 min- /max- 限制尺寸,确定加了 overflow: auto





盒模型



margin填充(主要给父元素设置overflow来触发父元素的BFC)





对应的盒模型

列表内容



absolute定位+margin填充





对应的盒模型



总结:*此方法就是利用定位,将子元素设置top和left 均为 50%,然后margin-top 和

margin-left设为负的本身盒子的高和宽的一半,即可实现水平垂直居中!*

transform居中

上面讲到的div居中的例子中,div的宽度都是固定的,然而实际项目中,有可能遇到不定宽的div,特别是响应式或者移动端的设计中,更加常见。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.parent{
float:left;
width:100%;
height:200px;
background-color:red;
}

.children{
float:left;
position:relative;
top:50%;
left:50%;

}

.children-inline{
position:relative;
left:-50%;
-webkit-transform:translate(0,-50%,0);
transform:translate(0,-50%,0);
background-color:#ccc;
color:#fff;
}
</style>
</head>
<body>
<div class="parent">
<div class="children">
<div class="children-inline">我是水平垂直居中噢!</div>
</div>
</div>

</body>
</html>




*首先我们利用float,将需要居中的div的父div也就是children的宽度收缩,然后left:50%,将children的左边与水平中线对齐。这个时候,还没有真正居中,我们需要将children-inner左移动-50%,这样就水平居中了。
再来说说垂直方向,先将children的top设为50%,然后其上边和垂直中线对齐了,同样,我们需要将children-inner上移动-50%。但是这个50%是计算不出来的,所以我们用到了transform
translate3d(0, -50%, 0); 这个方法非常好用噢。*

flex居中

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
html,body{
width:100%;
height:200px;
}

.parent{
display:flex;
align-items:center;//垂直居中
justify-content:center;
width:100%;
height:100%;
background-color:red;
}

.children{
background-color:blue;
}
</style>
</head>
<body>
<div class="parent">
<div class="children">flex水平垂直居中的</div>
</div>
</body>
</html>


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: