您当前的位置: 首页 >  css

命运之手

暂无认证

  • 3浏览

    0关注

    747博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

【CSS】【排列对齐】元素或内容在父div中居中显示的几种方式

命运之手 发布时间:2019-05-28 14:25:17 ,浏览量:3

在这里插入图片描述 ?绝对定位方式 这种方式要求父级div的display属性不等于static,子元素大小必须确定


    
        
#parent { width: 400px; height: 400px; background: yellow; position: relative; } #child { width: 200px; height: 200px; background: orange; position: absolute; top: 50%; left: 50%; margin-top: -100px; margin-left: -100px; }

?平移变换方式 和绝对定位方式原理一致,但因为平移距离可以用相当于自身的百分比来指定,因此子元素大小可以不确定


    
        
#parent { width: 400px; height: 400px; background: yellow; position: relative; } #child { width: 200px; height: 200px; background: orange; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }

?js定位方式 通过js来计算居中的位置并定位


    
        #parent {
            width: 400px;
            height: 400px;
            background: yellow;
            position: absolute;
        }

        #child {
            max-width: 80%;
            width: auto;
            height: auto;
        }
    

    
        $(() => {
            $parent = $("#parent");
            $child = $("#child");
            $child.offset({
                left: ($parent.width() - $child.width()) / 2,
                top: ($parent.height() - $child.height()) / 2
            });
        });
    

?flex布局方式 flex布局可以设置子元素排列对齐方式


    
        
#parent { width: 400px; height: 400px; background: yellow; display: flex; align-items: center; justify-content: center; } #child { width: 200px; height: 200px; background: orange; }

?flex布局的另一种方式 flex布局自动将margin=auto的子元素处理为居中


    
        
#parent { width: 400px; height: 400px; background: yellow; display: flex; } #child { width: 200px; height: 200px; background: orange; margin: auto; }

?grid布局方式 grid布局可以设置子元素的排列对齐方式


    
        
#parent { width: 400px; height: 400px; background: yellow; display: grid; justify-items: center; align-items: center; } #child { width: 200px; height: 200px; background: orange; }

?line-height方式 如果父div的内容只有单行文字,可以将line-height设置为和div等高,来让文字居中


    
        
Hello
#parent { width: 400px; height: 400px; background: yellow; text-align: center; line-height: 400px; }
关注
打赏
1654938663
查看更多评论
立即登录/注册

微信扫码登录

0.0435s