未知宽高元素垂直水平居中

6 篇文章 0 订阅

在前端布局中,不可避免的会让元素垂直水平居中,已达到某种效果,那么这个元素按照是否知道宽高来分为已知宽高,未知宽高

1.借助table的td中的元素


下面介绍的方法主要是利用display:inline-block;让元素变为行内块元素,利用vertical-align:middle来实现垂直居中,利用父元素的text-align:center;实现水平居中。

直接上例子吧

<!DOCTYPE html>
<html>
<head><style>
*{margin:0px; padding:0px;}
.wrap {
position:absolute;background-color:blue;width:100%;height:100%;text-align:center
}
.juzhong {
//下面这行要或者不要都可以,div是否有宽度和高度这种方法都可以
// width:200px;height:100px;

background-color:red;display:inline-block;
}
</style>
</head>
<body>
<table class='wrap' >
<tr>
<td><div class='juzhong' >hahhahaha</div></td></tr>

</table>
</body>

</html>

结果显示


其实上面这种方法说白了就是使得要居中的div变成table-cell包裹的元素,然后自己变为行级元素

<!DOCTYPE html>
<html>
<head><style>
*{margin:0px; padding:0px;}
.wrap {display:table-cell; width:300px; height:300px; text-align:center; vertical-align:middle; background:rgba(0,0,0,0.5);}
.test {background:red; display:inline-block;width:50px;height:50px;}
</style>
</head>
<body>
<div class="wrap">
<div class="test">
hah
</div>
</div>
</body>

</html>

结果如下:


2.另一种方法的是利用一个没有宽度b标签来实现水平垂直居中,但是很遗憾的是原理我没有搞懂,如果大家有明白的能否给我说下哈哈

<!DOCTYPE html>
<html>
<head><style>
*{margin:0px; padding:0px;}
.wrap {
background-color:blue;
text-align:center;
width:300px;
height:300px;
}
.wrap2 {
display:inline-block;
width:0px;
height:100%;
vertical-align:middle;

}
.test {
display:inline-block;
background-color:red;
}
</style>
</head>
<body>
<div class="wrap">
<b class="wrap2"></b>
<div class="test">
hha
</div>
</div>
</body>

</html>

结果如下:


3.借助transform:translate的方法,因为这个是按照自己本身做的偏移

代码:

<!DOCTYPE html>
<html>
<head><style>
*{margin:0px; padding:0px;}
.test {position: absolute; left:50%; top:50%; -webkit-transform:translate(-50%,-50%); transform:translate(-50%,-50%);background-color:blue;}
</style>
</head>
<body>
<div class="test">

<div style='width:300px;height:300px;'>hah</div>
//或者<div >hah</div>
</div>
</body>

</html>
但是上文在IE环境不支持

4.按照css3的新属性 box box-align:垂直居中box-center:水平居中

<!DOCTYPE html>

<html>
<head>
    <title>test</title>
</head>
<body >
<div style="width:300px; height: 300px; background-color: #ccc;
  line-height: 300px; text-align: center;">
    <div>sss</div>
</div>
<div style="width:300px; height: 300px; background-color: #aaa;
 display:-webkit-box;-webkit-box-pack: center;
   ; -webkit-box-align:center">
    <div style='background-color:blue;width:20px;height:20px;'>sss</div>
</div>
</body>
</html>





  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值