位置div在中间



这是代码:https://jsfiddle.net/twy161er/6/

HTML:

<div id="top">
Logo. Menu
</div>
<div id="content">
Text Text Text
</div>
<div id="bottom">
Text in the bottom
</div>

CSS:

#top {
  width: 100%;
  height: 100px;
  background-color: red;
}
#bottom {
  width: 100%;
  height: 100px;
  background-color: blue;
  margin: 0;
  bottom: 0;
  left: 0;
  overflow: hidden;
  position: absolute;
}
#content {
}

我希望"内容"div位于页面的中心和中间。

我该怎么做?

为三个DIV创建一个父div .main,并为内容文本添加一个换行DIV标记,并使用display table table-row table-cell

html, body {
  height: 100%;
  margin: 0;
}
.main {
	display: table;
	width: 100%;
	height: 100%;
}
.top {
	height: 0;                /* make it dynamic */
	background-color: red;
	display: table-row;
}
.bottom {
	height: 0;                /* make it dynamic */
	background-color: lime;
	display: table-row;
}
.content {
	display: table-row;
	vertical-align: middle;
	background: yellow;
}
.content div {
    text-align: center;
	vertical-align: middle;
	display: table-cell;
}
<div class="main">
  <div class="top">
    Logo. Menu<br />
    Dynamic content
  </div>
  <div class="content">
    <div>Text Text Text</div>
  </div>
  <div class="bottom">
    Text in the bottom<br />
    Dynamic content
  </div>
</div>

Jsfidle演示:https://jsfiddle.net/twy161er/15/

为什么要使用display:table?因为即使窗口高度小于200px,content text也总是显示;您可以获得IE8/9支持。

这很简单!

您可以使#content的内容如下:

<div id="content">
    <div>Text Text Text</div>
</div>

然后,你所需要做的就是添加这个CSS:

#content {}
#content div {
  position: absolute;
  padding: 0;
  margin: 0;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

解释

您首先absolute您的文本。然后,重置元素<div>marginpadding。然后,将内部<div>向下推页面高度的50%,并向左推页面宽度的50%。然后,你必须向左移动它,宽度的50%,向上移动它,高度的50%。这样,就可以得到<div>的确切中心。

工作示例:JSFiddle。

CSS规则"margin:auto"到#contentdiv应该将其水平放在中间。

为了将其放在屏幕中间,请尝试:

#content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

从这里获取如何在页面大于屏幕时将div定位在屏幕中间

请注意,您的顶部和底部div处于绝对位置,因此无法告诉#contentdiv相对于它们进行定位。

您的内容缺少对id"#"的引用。

我希望这能解决你的问题。

#content {
  display: table;
  margin: 0 auto;
}

最新更新