总结: CSS的居中操作

  • CSS居中算是一个比较基础的问题,在实际运用中,需要考虑到的一般是两种情况
    • 一种是主要是表现为文字,图片等行内元素的居中
    • 一种是指 div 等块级标签元素的居中

文字图片的居中

text-align: center

<div class="center">
  <span class="center_text">123</span>
</div>
.center{
  text-align:center;
}
center_text{
  display:inline-block;
  width:500px
}
  • 这种方式是在父元素中添加text-align:center时,直接子元素如果是inlineinline-block,那么子元素在父元素中居中

margin: 0 auto

<div class="center">
  <span class="center_text">
    块级元素 + 设置高度 + margin: 0 auto;
 </span>
</div>
.center_text {
  display: block;
  width: 500px;
  margin: 0 auto;
}
  • 这种对齐方式要求内部元素.content_text块级元素,并且不能脱离文档流(如设置position:absolute),否则无效。

块级标签元素的居中

脱离文档流的居中方式

<div class="mask">
 <div class="content">我是要居中的板块,</div>
</div>
.mask {
  display: block;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: #000;
  z-index: 1;
}

.content {
  display: block;
  position: fixed;
  width: 666px;
  height: 400px;
  top: 50%;
  left: 50%;
  margin-left: -333px;
  margin-top: -200px;
  /* transform: translate(-50%, -50%); */
  z-index: 2;
  background-color: #fff;
}
  • 把内部div设置宽高之后,再设置top、left各为50%,设置完之后,这里是按照左端居中的,接着我们使用负边距的方式调整,将margin-top设置为负的高度的一半,margin-left设置为负的宽度的一半,就可以居中了。也可以用 transform: translate(-50%, -50%); 替代margin-topmargin-left,直接一步到位

使用css3计算的方式居中元素calc

<div class="mask">
 <div class="content">我是要居中的板块,</div>
</div>
.mask {
  position: relative;
  width: 100vw;
  height: 100vh;
  border: 1px solid #ccc;
}

.content {
  position: absolute;
  top: calc(50% - 50px);
  left: calc(50% - 150px);
  width: 300px;
  height: 100px;
  border: 1px solid #000;
}
  • 这种方式同样是将脱离文档流的元素,然后使用计算的方式来设置top和left;


  今天是10月1号,国庆节,我起了个大早,忘记了今天不上班,刚刚去看了好声音,真不错,出门剪了个不漂亮的发型🙃 ,还吃了炸鸡,然后,然后就上火长痘痘了,ε=(´ο`*)))唉,.最后祝大家国庆快乐,祝我们祖国越来越强大 👍!!!

<iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=86 src="//music.163.com/outchain/player?type=2&id=1851244378&auto=1&height=66"></iframe>

<font size="2">最后更新于 2021-10-1</font>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。