zoukankan      html  css  js  c++  java
  • 如何居中一个浮动的元素--前端面试题

    搜索了一下网上的答案,分为两种:

    1、可以在外层加一个div,外层的div采用margin居中,里层的div设置宽度为100%。

    <html>
    <head>
    <title>居中的菜单</title>
    <style type="text/css">
    *{
        margin:0;
        padding:0;
        list-style:none;
    }
    html{
        height:100%;
    }
    body{
        
        height:100%;
    }
    .warp{
        width:960px;
        margin:15px auto;
        padding:5px 0;
        background:#333;
    }
    .menu{
        float: left;
        width:100%;
        overflow:hidden;
    }
    .menu ul{
        font: 12px/30px "Times New Roman", Times, serif;
        float:left;
        left:50%;
        margin:0 auto;
        position:relative;
    }
    .menu ul li{
        float:left;
        position:relative;
        right:50%;
        margin-left:2px;
    }
    .menu ul li a{
        display:block;
        padding:0 15px;
        text-decoration:none;
        color:#f30;
        background:#eee;
    }
    .menu ul li a:hover{
        background:#08f;
        color:#fff;
    }
    .clearfix:after{
        content: ".";
        display: block;
        height:0;
        clear:both;
        visibility:hidden;
    }
    .clearfix{
        zoom:1;
    }
    </style>
    </head>
    <body>
    <div class="warp clearfix">
        <div class="menu">
            <ul>
                <li><a href="#">PHP</a></li>
                <li><a href="#">ASP.NET</a></li>
                <li><a href="#">JQUERY</a></li>
                <li><a href="#">AJAX</a></li>
                <li><a href="#">EXTJS</a></li>
            </ul>
        </div>
    </div>
    </body>
    </html>

    2、设置当前div的宽度,然后设置margin-left:50%; position:relative; left:-250px;其中的left是宽度的一半。

    500px;height:300px; float:left; margin-left:50%; p osition:relative; left:-250px; background-color:#CCC; 

      设置margin-left:50%;后浮动元素左边正好位于文档中间,设置块相对定位position:relative;然后左移宽度的二分之一,即可实现元素居中。在这个实例中宽度500,left设置为-250px.

  • 相关阅读:
    CSUOJ 1170 A sample problem
    code forces 979C
    PAT L1 049 天梯赛座位分配
    牛客~~打篮球~~~模拟水题
    牛客~~扫雷~~~DFS+模拟
    模板整理~~~~~大整数模板
    湖南多校对抗赛网络赛第五场
    Educational Codeforces Round 42 (Rated for Div. 2) C
    Educational Codeforces Round 42 (Rated for Div. 2) B
    texture 资源 shader资源
  • 原文地址:https://www.cnblogs.com/junhey/p/4249548.html
Copyright © 2011-2022 走看看