只要三行css代码让任何元素居中
只要三行css代码让任何元素居中
麦可儿 发表于3年前
只要三行css代码让任何元素居中
  • 发表于 3年前
  • 阅读 11
  • 收藏 0
  • 点赞 0
  • 评论 0

移动开发云端新模式探索实践 >>>   

With just 3 lines of CSS (excluding vendor prefixes) we can with the help of transform: translateY vertically center whatever we want, even if we don’t know its height.

The CSS property transform is usally used for rotating and scaling elements, but with its translateYfunction we can now vertically align elements. Usually this must be done with absolute positioning or setting line-heights, but these require you to either know the height of the element or only works on single-line text etc.

So, to do this we write:

.element {
  position: relative;
  top: 50%;
  transform: translateY(-50%);}

That’s all you need. It is a similar technique to the absolute-position method, but with the upside that we don’t have to set any height on the element or position-property on the parent. It works straight out of the box, even in IE9!

To make it even more simple, we can write it as a mixin with its vendor prefixes:

@mixin vertical-align {
  position: relative;
  top: 50%;
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
  transform: translateY(-50%);}.element p {
  @include vertical-align;}

Or you can use the Sass placeholder selector to reduce code bloat in the output CSS:

%vertical-align {
  position: relative;
  top: 50%;
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
  transform: translateY(-50%);}.element p {
  @extend %vertical-align;}


  • 打赏
  • 点赞
  • 收藏
  • 分享
共有 人打赏支持
粉丝 1
博文 22
码字总数 11603
×
麦可儿
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: