前端 css实现内容居中的N中写法

水平居中

一、使用margin进行居中

DOM结构

<div class="container">
  <div class="box"></div>
</div>

CSS样式

body {
  margin: 0;
}
.container {
  width: 1000px;
  height: 600px;
  background: #5F9EA0;
}
.box {
  width: 300px;
  height: 200px;
  background: coral;

  margin: 0 auto;
}

预览效果

这种方式可以将元素本身相对于父级居中(仅限块级元素,非块级元素可以通过display: block;转换成块级)。

二、flex布局

DOM结构和效果和方法一是一样的,其中css修改如下

横向排列
.container {
  width: 1000px;
  height: 600px;
  background: #5F9EA0;
  display: flex;
  justify-content: center;
}
.box {
  width: 300px;
  height: 200px;
  background: coral;
}
纵向排列

因为交换了X轴Y轴 所以justify-content: center;需要改成align-items: center;

.container {
  width: 1000px;
  height: 600px;
  background: #5F9EA0;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.box {
  width: 300px;
  height: 200px;
  background: coral;
}

flex布局的实现 可以使div.container下的所有子元素水平居中对齐。
更多关于flex弹性布局,可以看一下菜鸟教程的这边文章 传送门

三、利用text-align进行居中

DOM结构和效果和方法一还是一样的,css部分进行了修改如下

.container {
  width: 1000px;
  height: 600px;
  background: #5F9EA0;
  text-align: center;
}
.box {
  width: 300px;
  height: 200px;
  background: coral;
  display: inline-block;
}

利用text-align: center对文本居中的原理,将块级元素转化为inline-block,从而实现元素的居中。

四、脱离文档流 相对父级绝对居中

DOM不变 效果同上
方法1

.container {
  position: relative;
  width: 1000px;
  height: 600px;
  background: #5F9EA0;
}
.box {
  position: absolute;
  left: 50%;
  margin-left: -150px;
  width: 300px;
  height: 200px;
  background: coral;
}

方法2

.container {
  position: relative;
  width: 1000px;
  height: 600px;
  background: #5F9EA0;
}
.box {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  width: 300px;
  height: 200px;
  background: coral;
}

第一种方法的想法是在left: 50%;之后利用margin-left返回自身一般的宽度使其居中,但是在盒模型有padding/border时各浏览器显示可能会不一致,也会增加自身宽度的计算难度。还有就是元素本身可能就是不定宽的。
第二种方法是在第一种方法上的优化利用transform: translateX(-50%),弥补了第一种方法的不足。但是在IE8及以下版本浏览器中不受支持。
这种脱离文档流居中的优势在于可以超出父级 高度且不影响父级。

五、相对浏览器绝对居中

这种居中的实现和上面一种方法相同,只需要修改需对其元素的positionfixed即可。
DOM结构

<div class="box"></div>

CSS样式

.box {
  position: fixed;
  width: 300px;
  height: 200px;
  background: coral;
  left: 50%;
  transform: translateX(-50%);
}

六、浮动实现居中

原理和方法四一样,不推荐这么用,一般常用的方法是一、二、四。

DOM结构

<div class="box"></div>

CSS样式

.box {
  position: relative;
  left: 50%;
  transform: translateX(-50%);
  float: left;
  width: 300px;
  height: 200px;
  background: coral;
}

未完待续…

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值