• css实现垂直上下布局的两种常用方法


    例子:将两个元素在

    垂直居中放置.

    方法一:使用 Flexbox 来实现。

    在下面的示例中,我将为

    元素添加样式,使其成为一个 Flex 容器,并使用 Flexbox 属性将其中的两个 元素垂直居中:

    import React from 'react';
    import './Component.css'; // 导入样式文件
    
    function Component() {
      return (
        <div className="container">
          <span className="centered">Span 1</span>
          <span className="centered">Span 2</span>
        </div>
      );
    }
    
    export default Component;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    在上述代码中,我们为

    元素添加了名为 .container 的样式类,并为两个 元素分别添加了名为 .centered 的样式类。

    然后,在样式文件(例如 Component.css)中,你可以使用 Flexbox 属性来实现垂直居中:

    .container {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 300px; /* 为示例添加一个高度 */
    }
    
    .centered {
      /* 可选的样式定义 */
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    我们通过将 .container 的 display 属性设置为 flex,以及设置 flex-direction: column;、align-items: center; 和 justify-content: center;,将其内部的元素在垂直方向上居中对齐。

    你可以根据需要对 .centered 类进行进一步的样式定义,例如设置文字样式、边距等。

    方法二:使用 Grid 实现上下布局

    你可以在容器上应用 Grid 布局,并使用网格行来定位上下两个元素。下面是一个使用 Grid 实现上下布局的示例:

    import React from 'react';
    import './Component.css'; // 导入样式文件
    
    function Component() {
      return (
        <div className="container">
          <div className="top">上方内容</div>
          <div className="bottom">下方内容</div>
        </div>
      );
    }
    
    export default Component;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    在上述代码中,我们在

    元素中包含了两个子元素,分别是上方内容和下方内容。

    然后,在样式文件(例如 Component.css)中,你可以使用 Grid 属性来实现上下布局:

    
    .container {
      display: grid;
      grid-template-rows: 1fr auto; /* 使用网格行实现上下布局 */
      height: 100vh; /* 为示例添加一个高度,这里使用视口高度作为容器高度 */
    }
    
    .top {
      background-color: #f1f1f1;
    }
    
    .bottom {
      background-color: #ddd;
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    在上述代码中,我们将 .container 的 display 属性设置为 grid,并使用 grid-template-rows 属性来定义网格行。1fr 表示第一行占据剩余的垂直空间,auto 表示第二行根据内容自动调整高度。

    .top 和 .bottom 元素则根据需要进行样式定义。

  • 相关阅读:
    Shiro入门(五)Shiro自定义Realm和加密算法
    最近踩的两条sql的坑
    深信服SG上网优化管理系统存在任意文件读取漏洞 附POC
    教你搞一个比较简单的计时和进度条装饰器 (多线程进阶版)
    JK405R-SOP16录音芯片ic方案的功能简介,可以内置录音30秒-高采样率
    前端程序员是怎么做物联网开发的
    css知识学习系列(2)-每天10个知识点
    2022/8/11
    Python如何用Numba加速科学计算和数据分析
    [ JavaScript ] JSON方法
  • 原文地址:https://blog.csdn.net/qq_43720551/article/details/132592036