• 【前端基础】垂直居中效果


    网页设计中,要实现垂直居中效果,可以尝试以下几种常见的方法:

    1. Flexbox 布局

      使用 Flexbox 布局是实现垂直居中效果的一种简单方法。以下是一个基本示例:

      <div class="container">
        <div class="centered-content">内容居中div>
      div>
      
      • 1
      • 2
      • 3
      .container {
        display: flex;
        align-items: center; /* 垂直居中 */
        justify-content: center; /* 水平居中 */
        height: 100vh; /* 使容器占据整个视口高度 */
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
    2. Grid 布局

      你也可以使用 CSS Grid 布局来实现垂直居中效果,类似于 Flexbox,但它更适合复杂的布局。

      <div class="container">
        <div class="centered-content">内容居中div>
      div>
      
      • 1
      • 2
      • 3
      .container {
        display: grid;
        place-items: center; /* 居中内容 */
        height: 100vh; /* 使容器占据整个视口高度 */
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
    3. 绝对定位

      使用绝对定位也可以实现垂直居中效果,但这通常需要明确定义容器的高度。

      <div class="container">
        <div class="centered-content">内容居中div>
      div>
      
      • 1
      • 2
      • 3
      .container {
        position: relative;
        height: 100vh; /* 使容器占据整个视口高度 */
      }
      
      .centered-content {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%); /* 通过平移来居中 */
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
    4. 表格布局

    还可以使用表格布局来实现垂直和水平居中效果,但这种方法不太常见。

    <div class="container">
      <div class="centered-content">内容居中div>
    div>
    
    • 1
    • 2
    • 3
    .container {
      display: table;
      width: 100%;
      height: 100vh; /* 使容器占据整个视口高度 */
    }
    
    .centered-content {
      display: table-cell;
      vertical-align: middle;
      text-align: center; /* 如果需要水平居中 */
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    1. 子元素是单行文本
    	.container {
    		height: 100px;
    		line-height: 100px;
    		text-align: center;
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    1. 绝对定位和 margin:auto
    	.centered-content{
    		position: absolute;
    		left: 0;
    		top: 0;
    		right: 0;
    		bottom: 0;
    		margin: auto;
    	} 
    	.container {
    		position: relative;
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    这些方法中的任何一个都可以用来实现垂直居中效果,具体取决于项目需求和个人偏好。选择其中一个并根据需要进行调整。

  • 相关阅读:
    超详细MySQL总结[从百草园到三味书屋]
    STC51单片机37——定时器流水灯
    Java中加减乘除的性能和位运算的性能比较
    没有不写注释的程序员,如果有,一定没看过别人的代码?
    DOM节点
    Java多线程之线程池(合理分配资源)
    【计算机视觉(7)】
    基于nodejs+vue学生论坛设计与实现
    helm 部署golang应用
    实现一个深克隆
  • 原文地址:https://blog.csdn.net/qq_44632227/article/details/132754782