CSS垂直居中整理

本文展示了在Vue.js组件中使用不同方法实现元素垂直居中的代码示例,包括弹性布局、定位、以及栅格布局。通过修改样式属性如align-items,justify-content,transform等,可以有效地将子元素在父元素内垂直居中显示。
摘要由CSDN通过智能技术生成

一、基本布局代码以及页面展示

<template>
  <div class="father">
    <div class="son"></div>
  </div>
</template>

<script>
export default {

}
</script>

<style>
.father{
  width: 600px;
  height: 600px;
  margin: 0 auto;
  border: 2px #000 solid;
}
.son{
  width: 100px;
  height: 100px;
  background: bisque;
}
</style>

 

注:为防止内容冗余,下面仅进行实现代码的展示 ,而不进行页面的展示

二、实现元素的垂直居中

1.通过弹性布局实现

<template>
  <div class="father">
    <div class="son"></div>
  </div>
</template>

<script>
export default {

}
</script>

<style>
.father{
  width: 600px;
  height: 600px;
  margin: 0 auto;
  border: 2px #000 solid;
  display: flex;
  /* 更改弹性布局垂直方向布局 */
  align-items: center;
  /* 更改弹性布局水平方向布局 */
  justify-content: center;
}
.son{
  width: 100px;
  height: 100px;
  background: bisque;
}
</style>

2.通过定位实现

<template>
  <div class="father">
    <div class="son"></div>
  </div>
</template>

<script>
export default {

}
</script>

<style>
.father{
  width: 600px;
  height: 600px;
  margin: 0 auto;
  border: 2px #000 solid;
  position: relative;
}
.son{
  position: absolute;
  top: 50%;
  left: 50%;
  /* transform 属性向元素应用 2D 或 3D 转换。该属性允许我们对元素进行旋转、缩放、移动或倾斜。 */
  /* translate 定义2D转换基于元素本身上左位移——50% */
  transform: translate(-50%,-50%);
  width: 100px;
  height: 100px;
  background: bisque;
}
</style>

3.通过栅格布局实现

<template>
  <div class="father">
    <div class="son"></div>
  </div>
</template>

<script>
export default {

}
</script>

<style>
.father{
  width: 600px;
  height: 600px;
  margin: 0 auto;
  border: 2px #000 solid;
  display: grid;
  /* 栅格布局垂直排序 */
  align-items: center;
  /* 栅格布局水平排序 */
  justify-content: center;
}
.son{
  width: 100px;
  height: 100px;
  background: bisque;
}
</style>

4.通过定位加margin实现

<template>
  <div class="father">
    <div class="son"></div>
  </div>
</template>

<script>
export default {

}
</script>

<style>
.father{
  width: 600px;
  height: 600px;
  margin: 0 auto;
  border: 2px #000 solid;
  position: relative;
}
.son{
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  margin: auto;
  width: 100px;
  height: 100px;
  background: bisque;
}
</style>

5.其他

其他的基本就是上面的混合使用了。就不多余进行说明了。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值