侧边栏壁纸
博主头像
落叶人生博主等级

走进秋风,寻找秋天的落叶

  • 累计撰写 130562 篇文章
  • 累计创建 28 个标签
  • 累计收到 9 条评论
标签搜索

目 录CONTENT

文章目录

只要三行css代码让任何元素居中

2023-12-15 星期五 / 0 评论 / 0 点赞 / 40 阅读 / 1885 字

With just 3 lines of CSS (excluding vendor prefixes) we can with the help oftransform:translateYvert

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;}


广告 广告

评论区