垂直居中Div元素

时间:2012-05-15 17:18:02

标签: html css vertical-alignment

我正在开发一个非常基本的网站模板,左上角有一个固定的标题,左下角有一个固定的底线。

中间的内容应该是居中的,我只是无法弄清楚我做错了什么。

问题1.)如果删除height: 100% css属性,为什么垂直居中不起作用?

问题2.)当在html标签上声明height: 100%时,为什么网站大于100%并超出浏览器窗口?

问题3.)为什么bottom-left显示正确,而不是bottom-right

问题4.)如果with设置为100%并且文本对齐到右边,则不要在右侧浏览器框架开始文本并向左延伸?为什么要扩展浏览器窗口?

非常感谢你的帮助。代码在下面可见

<!DOCTYPE html>
<html>
<head>
<style type="text/css">

html {
    height:100%;
}

body {
    height: 100%;
    margin-left: 20px;‚
}

.title {
    position: absolute;
    top: 20px;
    font-family: serif;
    font-size: 20px;
    text-align: left;
}

/* Center Text Section */

.area {
  width: 100%;
  height: 100%;
  position: relative;
}

.middlespace {
  position: absolute;
  left: 50%;
  top: 50%;
  display: table;
}

.middlespace p {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}

.exhibitionindex {
    text-align: center;
    width: 500px;
    margin-right: auto;
    margin-left: auto;
}

.bottom-left {

    position: absolute;
    bottom: 15px;
    text-align: left;
}

.bottom-right {
    position: absolute;
    bottom: 15px;
    text-align: right;
}

.exhibitiontitle {
    color: #d4d4d4;
    font-style: italic;
    font-family: sans-serif;
    font-size: 10px;
    text-align: center;
}

.bold {
    font-family: serif;
}


.about {
    font-size: 11px;
}

.contact {
    font-size: 11px;
}

.openinghours {
    font-style: italic;
    color: #8e8e8e;
    font-size: 11px;
}

</style>

<title>Website Title</title>

</head>
<body>
    <div class="title">Logo / Title Text</div>

    <div class="area">
        <div class="middlespace">
            <p>27. April 2012</p>
        </div>
    </div>
    <div class="bottom-left">
        <span class="about"><span class="bold">XYZ</span> is a project by Person One, Person Two, Person Three&nbsp;&nbsp;&#124;&nbsp;</span>
        <span class="contact">Website Information &mdash; <a href="mailto:info@info.com">info@info.com</a></span>
    </div>
    <div class="bottom-right"><span class="openinghours">Opening Hours Information</span></div>
</body>
</html>

1 个答案:

答案 0 :(得分:3)

  

问题1.)为什么如果我删除了垂直居中不起作用   身高:100%css属性?

默认情况下,htmlbody元素会扩展高度以适合其内容。因此,在不设置高度的情况下,html只有将内容包含为样式所需的高度。此外,绝对定位的元素不会影响其父母的大小。如果不将高度设置为100%,area也不会是窗口的整个高度,因此您将垂直居中在页面顶部的小条中。

  

问题2.)当高度:在html标签上声明100%时,为什么是   网站大于100%并超出浏览器窗口?

仅此一点不会超出页面边界。但是,如果向100%元素添加边距,边框或类似属性,则会将添加添加到100%,使您的元素延伸到窗口边缘。

  

问题3.)为什么左下角显示正确,但没有   右下?

您绝对定位这些元素。 Div元素通常是父元素宽度的100%。但是,当您绝对定位它们时,它们的宽度会缩小以适合内容。在您的情况下,您尝试text-align在默认情况下左对齐的div内。因为div仅与文本一样大,所以左,右和中心对齐看起来都一样。因为您已经绝对定位div,所以只需使用绝对定位来对齐它们:

.bottom-left {
    position: absolute;
    bottom: 15px;
    left: 15px;
}
.bottom-right {
    position: absolute;
    bottom: 15px;
    right: 15px;
}
相关问题