元素水平垂直居中的三种方法
- 缺点:必须知道元素的宽高
.box{ weight:200px; height:200px; position:absolute; left:50%; top:50%;/*设置元素的左外边距、上外边距为宽高的负1/2*/ margin-left:-100px; margin-top:-100px;}
- 缺点:兼容性不好,只支持IE9+的浏览器。如果不生效就加上margin:0 auto试试
.box{ weight:200px; height:200px; position:absolute;/*设置元素的定位位置,距离上、左都为50%*/ left:50%; top:50%;/*设置元素的相对于自身的偏移度为负50%(也就是元素自身尺寸的一半)*/ transform:translate(-50%,-50%); }
.box{ weight:200px; height:200px;position:absolute; left:0; right:0; top:0; bottom:0; margin:auto;}
图片在div中水平垂直居中
第一种方法:
<div class="center">
<a href="#"><img src="" /></a>
</div>
.center{width:160px;height:98px;overflow:hidden;text-align:center;}
.center a{display:table-cell;vertical-align:middle;width:160px;height:98px;}
.center a img{margin:0 auto;max-width:160px;max-height:98px;}
第二种方法:
<div class="logos-img"><img src="default_logo.png"></div>
.logos-img { border:1px solid #ccc; display: -webkit-flex; display: flex; flex-direction: row; justify-content: flex-start; flex-wrap: wrap; align-content: center; align-items: center; width: 70px;height: 70px; margin: 0 auto; overflow: hidden; }
.logos-img img { display:block; margin: 0 auto; width: auto;/*图片自适应不变形*/ max-width: 100%;/*宽度太大的图片按父级的100%显示*/ }
元素内容水平垂直居中
<div>哈哈哈哈哈哈</div>
div{ width: 100px;height: 100px;background: #ccc;display: flex;display: -webkit-flex;display: -webkit-box;display: -moz-box;display: -ms-flexbox; align-items: center; -webkit-align-items: center;box-align: center;-moz-box-align: center;-webkit-box-align: center;}
段落文字垂直居中显示
<div id="wrap">
<p id="content">现在我们要使这段文字垂直居中显示</p>
</div>
body { font-size: 12px; font-family: tahoma; }
div#wrap { height: 200px; display: table; text-align:center;}
p#content { vertical-align: middle; display: table-cell; background: #ccc; width: 760px; }
1920px的图片水平垂直居中
<style type="text/css">
*{ margin:0; padding:0;}
body { overflow-x: hidden;}
.imgWrap { text-align: center;align-items: center;}
.imgWrap a{ text-align: center; display: flex; flex-direction: column; justify-content: center; align-items: center;}
</style>
<div class="imgWrap">
<a href="#"><img src="" style="border:1px solid #eee;" alt=""></a>
</div>