当前位置:   article > 正文

css实现上下左右居中_css 上下居中

css 上下居中

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录


前言

提示:以下是本篇文章正文内容,下面案例可供参考

一、css居中

水平居中:使用text-align: center;来使文本和内联元素水平居中。对于块级元素,可以将其左右外边距设置为auto,例如margin-left: auto; margin-right: auto;来使其在父容器中水平居中。

垂直居中:使用vertical-align: middle;来使内联元素在垂直方向居中。对于块级元素,可以使用flexbox或grid布局来实现垂直居中。示例代码如下:

/* 使用flexbox布局实现垂直居中 */
.container {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
}

/* 使用grid布局实现垂直居中 */
.container {
  display: grid;
  place-items: center; /* 水平和垂直居中 */
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

上下左右居中:使用绝对定位(position: absolute)和top: 50%; left: 50%; transform: translate(-50%, -50%);来实现上下左右居中。这种方法是通过将元素的左上角位置放置在父容器的正中心,并使用translate(-50%, -50%)将元素往左上角偏移自身尺寸的一半,从而实现居中效果。

示例代码如下:

.container {
  position: relative; /* 父容器设置为相对定位 */
}

.centered-element {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

表格布局(Table Layout):通过将元素放置在表格单元格中,并使用display: table;和相关的表格布局属性来实现居中。示例代码如下:

.container {
  display: table;
  width: 100%; /* 父容器宽度设置 */
}

.centered-element {
  display: table-cell;
  text-align: center; /* 水平居中 */
  vertical-align: middle; /* 垂直居中 */
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

使用Flexbox和margin: auto;:使用Flexbox布局,设置align-items: center; justify-content: center;使元素在水平和垂直方向上居中,并将元素的外边距设置为auto来实现自动填充剩余空间。示例代码如下:

.container {
  display: flex;
  align-items: center;
  justify-content: center;
}

.centered-element {
  margin: auto;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

面试常考

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/702737
推荐阅读
相关标签
  

闽ICP备14008679号