垂直居中的元素

时间:2013-11-20 19:05:54

标签: css css3

我需要在标题中垂直对齐CSS多个元素。

目前,我正在使用这种结构:

-Header
 -Content div (This only set my width to 940 with paddings of 10px each side)
  -Element 1 (Height: Known, 50px)
  -Element 2 (Height: Unknown, bigger fonts)
  -Element 3 (Height: Unknown, smaller fonts)

所以我需要垂直对齐中间(我的标题的50% - 元素的大小)我的所有元素,我需要使它跨浏览器兼容......

我通过搜索来找到一些建议,例如使用浮动div,但是我很难尝试对齐所有元素,因为它们的大小并不相同......

修改 根据要求,这是我的HTML和CSS:

HTML:

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="../CSS/mediadevis.css" />
</head>

<body>
    <header>
        <div class="content">
            <div id="logo"></div>
            <nav>
                <ul>
                    <li>Accueil</li>
                    <li>Nos services</li>
                    <li>Notre compagnie</li>
                    <li>Nous joindre</li>
                </ul>
            </nav>
            <div id="lang">English</div>
        </div>
    </header>
</body>
</html>

CSS:

body {
    margin: 0;
    background-color: #336699;
}

header{
    background-image:url('../IMG/bg_top.png');
    height: 90px;
}

nav > ul{
    float: left;
    list-style-type:none;
    margin:0;
    margin-left: 10px;
    padding:0;
    color: #ffffff;
}

nav > ul > li{
    display: inline;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 20px;
    padding: 10px;
}

.content{
    margin: auto;
    width: 940px;
    padding-right: 10px;
    padding-left: 10px;
}

#lang{
    float: left;
}

#logo{
    background-image:url('../IMG/logo.png');
    height: 50px;
    width: 180px;
    float: left;
}

1 个答案:

答案 0 :(得分:1)

尝试Smashing Magazine的这些建议:

http://coding.smashingmagazine.com/2013/08/09/absolute-horizontal-vertical-centering-css/

具体来说,尝试此代码,使用TOP,LEFT,RIGHT和BOTTOM属性来定位元素:

HTML

    <div class="magix">
      magix!
    </div>
    <div class="more-magix">
        More Magix!
    </div>

CSS

.magix{
            background: red;
            bottom: 0;
            height: 100px;
            left: 0;
            margin: auto;
            position: absolute;
            top: 0;
            right: 0;
            width: 100px;
        }
        .more-magix {
            background: blue;
            bottom: 0;
            height: 100px;
            left: 0;
            margin: auto;
            position: absolute;
            top: 500px;
            right: 0;
            width: 100px;
        }

或者,查看Chris Coiyer的方法:

http://css-tricks.com/centering-in-the-unknown/