3号慢行者

导航

20170824:面试题笔记

 

 

1.如何水平居中一个元素:

 

 

(1)正常流inline元素:

父元素设置text-align:center。

(2)正常流block元素:

1)元素设置宽度;

2)左右margin值为auto;

3) IE6下需元素设置text-align:center。

 

<body>
    <div class="content">
    aaaaaa aaaaaa a a a a a a a a
    </div>
</body>

<style>
    body {
        background: #DDD;
        text-align: center; /* 3 */
    }
    .content {
        width: 500px;      /* 1 */
        text-align: left;  /* 3 */
        margin: 0 auto;    /* 2 */

        background: purple;
    }
</style>

 

(3) 浮动元素:

1)元素设置宽度;

2) 元素设置relative;

3)浮动方向设置偏移量(left或right:50%);

4)元素浮动方向上的margin设置为元素宽度的一半*-1;

<body>
    <div class="content">
    aaaaaa aaaaaa a a a a a a a a
    </div>
</body>

<style>
    body {
        background: #DDD;
    }
    .content {
        width: 500px;         /* 1 */
        float: left;

        position: relative;   /* 2 */
        left: 50%;            /* 3 */
        margin-left: -250px;  /* 4 */

        background-color: purple;
    }
</style

 (4)绝对定位元素:

   方法一:

1)为元素设置宽度,

2)偏移量设置为50%,

3)偏移方向外边距设置为元素宽度一半乘以-1

<body>
    <div class="content">
    aaaaaa aaaaaa a a a a a a a a
    </div>
</body>

<style>
    body {
        background: #DDD;
        position: relative;
    }
    .content {
        width: 800px;

        position: absolute;
        left: 50%;
        margin-left: -400px;

        background-color: purple;
    }
</style>

   方法二:

1)为元素设置宽度,

2)设置左右偏移量都为0,

3)设置左右外边距都为auto

    body {
        background: #DDD;
        position: relative;
    }
    .content {
        width: 800px;

        position: absolute;
        margin: 0 auto;
        left: 0;
        right: 0;

        background-color: purple;
    }
</style>

2.如何竖直居中一个元素

(1)单行文本:

  • 需要居中元素为单行文本,为包含文本的元素设置大于font-sizeline-height;

 (2)  其他:http://blog.csdn.net/freshlover/article/details/11579669

 

posted on 2017-08-24 09:11  3号慢行者  阅读(106)  评论(0编辑  收藏  举报