CSS-如何居中嵌套div?

问题描述 投票:6回答:5

CSS的新手。

我正在尝试使用以下代码将嵌套的div居中

HTML

<html>
    <head>
        <title>My website</title>
        <link rel="stylesheet" type="text/css" href="css/main.css" />
    </head>
    <body>
        <div id="wrapper">
            <div id="formpanel">
                <div id="loginForm">
                </div>
            </div>
        </div>
    </body>
</html>

CSS

body {
    margin: 0;
    background : #90ADB7 url('images/background.png') repeat-x;
    font-family: verdana, sans-serif;
    font-size: 0.85em;

}

#wrapper {
    width: 960px;
    margin: 0 auto;
    border-style:solid;
    padding: 190px 0;
}

#formpanel {
    width: 400px;
    height: 400px;
    background-color: yellow;
    margin: auto;
}

#loginForm {
    margin: auto;
    width: 50%;
    height: 50%;
    background-color:blue;
}

问题在于,最里面的div(#loginForm)与外部div(#formpanel)的顶部边缘齐平。我应该如何使内部div居中?

截屏“在此处输入图像描述”

css html centering
5个回答
4
投票

您可以使用相对定位:

http://jsfiddle.net/a879W/


2
投票
#formpanel {
    position: relative;
    ...
}

#loginForm {
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -100px;
    margin-left: -100px;
    width: 200px;
    height: 200px;
    background-color:blue;
}

2
投票
#loginForm {
  position:absolute;
  top:25%;
  margin: auto;
  width: 50%;
  height: 50%;
  background-color:blue;
}

编辑:顶部:25%而不是50%。


0
投票

您可以使用绝对定位:

#formpanel {
    width: 400px;
    height: 400px;
    background-color: yellow;
    margin: auto;
    position:relative;
}

#loginForm {
    position: absolute;
    width: 200px;
    height:200px;
    left: 100px;
    top: 100px;
    background-color:blue;
}

0
投票

// CSS代码(index.css)

.outer{
    position: relative;
    height: 500px;
    width: 500px;
    background-color: aqua;
    margin: auto;
}
.middle{
    position: absolute;
    height: 300px;
    width: 300px;
    background-color: blue;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
}
.inner{
    position: absolute;
    height: 100px;
    width: 100px;
    background-color: fuchsia;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
}

// html代码(index.html)

<!DOCTYPE html>
    <html lang="en">
        <head>
            <link rel="stylesheet" href="index.css">
        </head>
        <body>
            <div class="outer">
                <div class="middle">
                    <div class="inner"></div>
                </div>
            </div>
        </body>
    </html>
© www.soinside.com 2019 - 2024. All rights reserved.