css div居中布局及居右布局

互联网   发布时间:2009-06-06 16:35:37   作者:jb51   我要评论
居中布局是最基本的布局方式,下面会通过示例展示如何设置css样式实现居中布局,感兴趣的朋友跟随小编一起看看吧
(福利推荐:【腾讯云】服务器最新限时优惠活动,云服务器1核2G仅99元/年、2核4G仅768元/3年,立即抢购>>>:9i0i.cn/qcloud

(福利推荐:你还在原价购买阿里云服务器?现在阿里云0.8折限时抢购活动来啦!4核8G企业云服务器仅2998元/3年,立即抢购>>>:9i0i.cn/aliyun

概述

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

居中分析

  • 方法一:在父元素使用如下样式
    • display: flex;

    • align-items: center; //上下居中

    • justify-content: center;//左右居中
  • 方法二:需要父元素和子元素按照如下的样式进行设置
    • 父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;

到此这篇关于css div居中布局及居右布局的文章就介绍到这了,更多相关css div居中布局内容请搜索程序员之家以前的文章或继续浏览下面的相关文章,希望大家以后多多支持程序员之家!

相关文章

最新评论

?


http://www.vxiaotou.com