美文网首页
css居中小妙招

css居中小妙招

作者: 爱美的程序媛 | 来源:发表于2020-06-09 11:03 被阅读0次

身为前端,与样式打交道是必不可少的。每次拿到设计小姐姐的设计稿,你就会发现横向、纵向居中是设计小姐姐们的最爱。下面我就来总结一下居中常用的方法吧(喜欢就收藏哦😊)


(1)元素本身居中

a、使用line-height


<div class="box">我是box的文字</div>

.box{

        border: 1px solid #666;

        border-radius: 10px;

        width: 120px;

        height: 30px; 

        line-height: 30px;  /*line-height要和height设置成一样*/

        text-align: center; /*文本内容居中*/

    }

效果如下:

image

b、使用padding居中

.box{

    border: 1px solid #666;

    border-radius: 10px;

    padding: 5px 30px

}

效果如下(简单大方):

image

(2)子元素在父元素居中


<div class="parent">

        <div class="child">我是子元素</div>

    </div>

a、使用position

子元素有宽度和高度时


.parent{

        width: 600px;

        height: 600px;

        border: 1px solid #666;

        margin: 0 auto;

        margin-top: 60px;

        border-radius: 10px;

        position: relative;

    }

    .child{

        background: pink;

        width: 200px;

        height: 200px;

        border-radius: 10px;

        position: absolute;

        left: 50%;

        top: 50%;

        margin-top: -100px;

        margin-left: -100px;

    }

效果如下:

image

子元素无具体宽高时:


.parent{

        width: 600px;

        height: 600px;

        border: 1px solid #666;

        margin: 0 auto;

        margin-top: 60px;

        border-radius: 10px;

        position: relative;

    }

    .child{

        background: pink;

        border-radius: 10px;

        position: absolute;

        left: 50%;

        top: 50%;

        transform: translate(-50%, -50%);

    }

效果如下:

image

b、使用flex居中(好用实力推荐)


.parent{

        width: 600px;

        height: 600px;

        border: 1px solid #666;

        margin: 0 auto;

        margin-top: 60px;

        border-radius: 10px;

        display: flex;

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

        justify-content: center; /* 左右居中*/

    }

    .child{

        background: pink;

        border-radius: 10px;

    }

效果同上哦


有了这些小妙招,再也不怕设计小姐姐的设计稿了😄😄😄。

相关文章

  • css居中小妙招

    身为前端,与样式打交道是必不可少的。每次拿到设计小姐姐的设计稿,你就会发现横向、纵向居中是设计小姐姐们的最爱。下面...

  • CSS居中小结

    CSS居中总结 最近在学习CSS居中,居中里面又包含水平居中和垂直居中,分不太清内联元素(inline or in...

  • CSS居中小结

    博客原文地址:Claiyre的个人博客 https://claiyre.github.io/如需转载,请在文章开头...

  • CSS居中小技巧

    Ⅰ、水平居中设置-行内元素 Ⅱ、水平居中设置-定宽块状元素 Ⅲ、水平居中总结-不定宽块状元素方法 (一) (二) ...

  • CSS居中小结

    下面是CSS居中的几种方法: 水平居中元素: 通用方法,元素的宽高未知 方式一:CSS3 transform 方式...

  • CSS居中小结

    一、水平居中 block元素的水平居中如果block宽度写死了,采用: 如果block宽度没写死,那就: 行内元素...

  • css居中小结

    1.水平居中方法 如果居中的对象是一个inline行内元素。那么就给他一个爸爸容器,爸爸容器的类型为block元素...

  • CSS居中小结

    CSS中在不同场景下,解决居中的方式有很多,经常让人无从下手,所有我们将CSS居中进行一次小结,方便以后我们布局使...

  • CSS 居中小结

    行内元素居中: 常用的行内元素比如文本、图片、按钮等,可以通过给父元素添加一个:text-align:cent...

  • CSS 居中小结

    水平居中 行内或类行内元素 在块级父容器中让行内元素居中,只需使用 text-align: center; : 这...

网友评论

      本文标题:css居中小妙招

      本文链接:https://www.haomeiwen.com/subject/stkstktx.html