div 怎么设置垂直水平居中?? 要宽高都是100%

kuaidi.ping-jia.net  作者:佚名   更新日期:2024-07-31
怎么设定一个div垂直和水平都居中在css样式中




图片与文本内容混合图片与文本内容混合




样式:.frame{
float:left;
margin:2px;
}
.outer {
height: 250px;
width: 240px;
overflow: hidden;
background:gold;
position: static !important;
position: relative;
display: table !important;
}
#middle { /* for explorer only*/
position: absolute;
top: 50%;
}
#middle[id] {
display: table-cell;
vertical-align: middle;
position: static;
}
#inner { /* for explorer only */
position: relative;
top: -50%;
width: 100%;
margin: 0 auto;
text-align:center
}

方法一:
用一个“ghost”伪元素(看不见的伪元素)和 inline-block / vertical-align 可以搞定居中,非常巧妙。但是这个方法要求待居中的元素是 inline-block,不是一个真正通用的方案。
html如下:


haorooms案例题目
haorooms案例内容,haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容


css如下:
/* This parent can be any width and height */
.block {
text-align: center;
}
/* The ghost, nudged to maintain perfect centering */
.block:before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -0.25em; /* Adjusts for spacing */
}
/* The element to be centered, can
also be of any width and height */
.centered {
display: inline-block;
vertical-align: middle;
width: 50%;
}
方法二:
可以用table布局方法,但是这种方法也有局限性!
写法如下:



Unknown stuff to be centered.



由于table写法比较费时,你也可以用div代替table,写法如下:
html:


Unknown stuff to be centered.


css:
.something-semantic {
display: table;
width: 100%;
}
.something-else-semantic {
display: table-cell;
text-align: center;
vertical-align: middle;
}
方法三,终极解决方法:
以上2中方法可能都有其局限性,我介绍的第三中方法是比较成熟的不是固定高宽div的垂直居中的方法!但是方法是css3的写法,想兼容IE8的童鞋们,建议用上面的方法!
方法和我们固定高宽的差不多,但是不用margin我们用的是 translate()
demo如下:




haorooms不固定高度div写法

.center {
position: fixed;
top: 50%;
left: 50%;
background-color: #000;
width:50%;
height: 50%;
-webkit-transform: translateX(-50%) translateY(-50%);
}






我上面的css只是针对webkit内核的浏览器,其他内核浏览器写法如下:
-webkit-transform: translateX(-50%) translateY(-50%);
-moz-transform: translateX(-50%) translateY(-50%);
-ms-transform: translateX(-50%) translateY(-50%);
transform: translateX(-50%) translateY(-50%);

宽度简单就是 width:100% 高度的话 你给 body 设 height:100% 然后 那个大的 DIV 的高度也设 100% 就可以了!

margin:auto;