CSS动态地将div放在中心元素旁边

时间:2011-08-09 06:09:45

标签: css layout html

我有一个设计问题。我在页面上有一个居中的徽标,我想要的是一个以页面左侧和徽标左侧为中心的div。

我怎样才能使用css实现这个目标?

以下是示例: Sample of the expected result

3 个答案:

答案 0 :(得分:2)

看看这个演示......

http://jsfiddle.net/UnsungHero97/7Z5fu/

HTML

<div id="wrapper">
    <div id="box-left">
        <div id="left"></div>
    </div>
    <div id="box-center">
        <div id="center"></div>
    </div>
</div>

CSS

html, body {
    margin: 0 !important;
    padding: 0 !important;
}

#wrapper {
    width: 100%;
}

#box-center, #box-left {
    width: 50%;
    float: left;
}

#left {
    border: 1px solid magenta;
    height: 50px;
    width: 50px;
    position: relative;
    left: 50%;

    /* half of width of #left + half of margin-left of #center */
    margin-left: -75px; /* 50/2 + 100/2 = 25 + 50 = 75 */
}

#center {
    border: 1px solid magenta;
    height: 50px;
    width: 200px;
    margin-left: -100px;
}

我希望这会有所帮助。

答案 1 :(得分:1)

如果可以修复徽标宽度,它将起作用,这是代码。

HTML:

<div id="logo"><img src="https://encrypted.google.com/images/logos/ssl_logo.png"></div>

<div id="otherdiv"><img src="https://encrypted.google.com/images/logos/ssl_logo.png"></div>

CSS:

#logo {
        width: 100px;
        height: 50px;
        position: absolute;
        top: 50px;
        left: 50%;
        margin-left: -50px;
        text-align: center;
    }

    #otherdiv {
        text-align: center;
        position: absolute;
        top: 50px;
        left: 0;
        width: 50%;
        margin-left: -50px; /* Half of the logo width */
    }

    #logo img,
    #otherdiv img {
        width: 100px;
    }

    #otherdiv img {
        margin-left: 50px; /* Half of the logo width */
    }

答案 2 :(得分:0)

这里我左右分开了两个div,leftDiv中有一个div,X_div将其设为width:20%margin:0 auto。如果扩展分辨率,x_div也将根据您的要求进行扩展。

#leftDiv {
width:30%;
height:auto;
}


#leftDiv X_Div {
width:20%;
height:auto;
margin:0 auto;
}


#rightDiv {
width:70%;
height:auto;
}
相关问题