简体   繁体   English

如何将div放在另一个div中?

[英]How to center div within another div?

I'm learning how to use the position relative/absolute. 我正在学习如何使用位置相对/绝对。

However, I've come a little stuck. 但是,我有点陷入困境。

I'm trying to horizontally center a div within a div but when I add margin: 0 auto; 我试图在div中水平居中div,但是当我添加margin: 0 auto; it does nothing. 它什么都不做。

I've made a Fiddle. 我做了一个小提琴。

Or here's the code: 或者这是代码:

<!DOCTYPE HTML>
<html lang="en-UK">
    <head>
        <link href="DivTest.css" rel ="stylesheet" type="text/css">
        <title></title>
    </head>
    <body>
    <div id="header"></div>
    <div id="outer">
        <div id="inner"></div>
    </div>
    </body>
</html>

CSS: CSS:

body, html {
     margin: 0;
     width: 100%;
}

#header{
     position: relative;
     width: 100%;
     height: 200px;
     background-color: lightgreen;
     margin: 0 0 20px 0;
}

#outer{
     position: relative;
     width: 800px;
     height: 500px;
     background-color: red;
     margin: 0 auto;

}

#inner{
     position: absolute;
     width: 200px;
     height: 250px;
     background-color: lightblue;
     margin: 0 auto;
}

Any help would be appreciated. 任何帮助,将不胜感激。

Just remove the position:absolute; 只需删除position:absolute; property for #inner #inner财产

Fiddle: http://jsfiddle.net/Q8NVH/7/ 小提琴: http//jsfiddle.net/Q8NVH/7/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM