繁体   English   中英

CSS-对齐中心

[英]CSS - align center

我终于想消除表并使用CSS。

我有3个DIV,它们构成了三层布局:页眉,正文和页脚。 我现在正尝试在这些图层的顶部覆盖900px宽的DIV,居中对齐,以容纳我的一些内容和导航按钮。

这些是3层:

在此处输入图片说明

而这(在Photoshop中完成)是我想要实现的,但对眼睛透明:

在此处输入图片说明

我的3个基本层的编码如下:

<div id="main" style="width:100%; z-index:1; position:relative;">
    <div id="header" style="width:100%; height:175px; text-align:center; background:#151515; z-index:1;"></div>
    <div id="contents" style="width:100%; height:400px; position:relative; background:#FFF; z-index:1;"></div>
    <div id="footer" style="width:100%; height:200px; position:relative; background:#151515; z-index:1;"></div>
</div>

我确实设法使一个新层位于顶部,但是并没有居中对齐。 有人可以指出正确的方向吗?

这样的事情可能会有所帮助:

JSFiddle: http : //jsfiddle.net/DSH5J/

加:

<div id="square"></div>

#square {
    position: absolute;
    top:0;
    bottom:0;
    left:0;
    right:0;
    margin:0 auto;
    margin-top:50px;
    width:80%;
    height:100%;
    background-color:#333;
    z-index:10;
}

设置宽度,并将margin-left和margin-right设置为auto。 不过,这仅适用于水平。 如果您想同时使用两种方式,则只需同时进行。

margin-left:auto;
margin-right:auto;

我知道将已知宽度的div居中的最简单方法是为其指定以下样式:

position: absolute;
left: 50%;
width: 900px;
margin-left: -450px;

“把钱放在嘴里”: http : //jsfiddle.net/YVmBU/2/

HTML:

<div id="main">
    <div id="header"></div>
    <div id="contents-box">
        <div id="contents">
            <p>Some text</p>
            <p>etc</p>
            <p>etc</p>
            <p>etc</p>
            <p>etc</p>
            <p>etc</p>
        </div>
    </div>
    <div id="footer"></div>
</div>

CSS:

#main {
}
#header {
    position: relative;
    height:100px;
    background:#151515;
    z-index: -1;
}
#contents-box {
    border: dashed grey 1px; /* for understanding only, remove it in the end */
    z-index: 1;
    margin-top: -30px;
    margin-bottom: -30px;
    /* TODO: address min-height; try only one line of text. */
    /* fixed height would work too, but would not let the box stretch dynamically */
}
#contents {
    width: 75%;
    height: 100%;
    margin: 0 auto;
    background: grey;
    z-index: 1;
}
#footer {
    position: relative;
    height:75px;
    background:#151515;
    z-index: -1;
}

唯一的问题是文本内容很少:如果在#content上使用min-height,则当文本很少时,灰色背景不会伸展; 如果使用的是N px的静态高度,则该框不会动态扩展。

但是,如果内容很少时合并两个黑条并不重要,请忽略它。


删除灰色虚线边框和灰色背景; 这些都是帮助者-知道每个盒子在哪里,了解发生了什么。

顺便说一句,位置:相对位置必须在z-index: -1; 层,否则背景不会消失。 继续阅读位置信息:这是因为html中的内容具有position: static默认情况下为position: static ,而z-index的行为取决于位置。
您可以在此页面中阅读以下内容: http : //tjkdesign.com/articles/z-index/teach_yourself_how_elements_stack.asp

唯一的问题是文本内容很少:如果在#content上使用min-height,则当文本很少时,灰色背景不会伸展; 如果使用的是N px的静态高度,则该框不会动态扩展。

但是,如果内容很少时合并两个黑条并不重要,请忽略它。

暂无
暂无

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

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