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


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

    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

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

  • 相关阅读:
    鼎捷前端开发校招岗技术面面经(已过)
    基于mediasoup的webrtc server,性能压测时发现带宽利用率偏低(40%)
    MATLAB 工具箱路径缓存
    java学习--day23(线程池)
    OpenGL ES之深入解析PBO、UBO与TBO的功能和使用
    Tomcat的负载均衡、动静分离
    Linux系统编程 系统编程概念
    .NET餐厅管理系统user数据帮助类增删改查管理员信息
    【多线程案例】Java实现简单定时器(Timer)
    Q_PLUGIN_METADATA
  • 原文地址:https://blog.csdn.net/qq_44632227/article/details/132754782