css div居中布局 居右布局
  JZjRRktyDDvK 2024年04月11日 34 0

概述

居中布局是最基本的布局方式,下面会通过示例展示如何设置css样式实现居中布局

居中示例

<body>
    <div style="display: flex;">
        <!--不设置样式,左上角对齐-->
        <div class="first-div">
            <div class="second-div">
            </div>
        </div>
        <div class="first-div center-one">
            <div class="second-div"> 
            </div>
        </div>
        <div class="first-div" style="display: flex;">
            <div class="second-div center-inner"> 
            </div>
        </div>
    </div>
    <style>
        .first-div
        {
            width:100px;height: 100px; 
            margin-left:10px;
            background: gray;
           
        }
        .second-div
        {
            width:50px;height: 50px;background: green;
        }
        .center-one
        {
           
            display: flex; 
            align-items: center;
            justify-content: center;
        }
        .center-inner
        {
            margin: auto;
        }
    </style>
</body>

 

居中分析

  1. 方法一:在父元素使用如下样式
    • display: flex;
    • align-items: center; //上下居中
    • justify-content: center;//左右居中
  2. 方法二:需要父元素和子元素按照如下的样式进行设置
    • 父div使用display: flex;
    • 子元素使用margin: auto;
    • 如果只需要上下居中使用margin-top:auto, margin-bottom:auto

居右布局示例

 

<body>
    <div style="display: flex;">
        <!--不设置样式,左上角对齐-->
        <div class="first-div">
            <div class="second-div">
            </div>
        </div>
        <div class="first-div">
            <div class="second-div right-one"> 
            </div>
        </div>
        <div class="first-div right-two">
            <div class="second-div"> 
            </div>
        </div>
    </div>
    <style>
        .first-div
        {
            width:100px;height: 100px; 
            margin-left:10px;
            background: gray;
           
        }
        .second-div
        {
            width:50px;height: 50px;background: green;
        }
        .right-one
        {
           
            float: right;
        }
        .right-two
        {
            display: flex;
            justify-content: right;
        }
    </style>
</body>

 

居右分析

  • 方法一:在子元素使用样式 float:right即可
  • 方法二:在父元素使用样式
    • display: flex;
    • justify-content: right;

 

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2024年04月11日 0

暂无评论

推荐阅读
  JZjRRktyDDvK   2024年04月11日   34   0   0 Html/Css
  yFRq1xYnAob9   22天前   20   0   0 Html/Css
JZjRRktyDDvK