巨大的石头

在这里寻找精彩人生

导航

css div居中布局 居右布局

概述

居中布局是最基本的布局方式,下面会通过示例展示如何设置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;

 

posted on 2024-04-10 22:56  巨大的石头  阅读(107)  评论(0编辑  收藏  举报

打赏