繁体   English   中英

将Div元素垂直居中

[英]Centering Div Element vertically

我正在研究一个非常基本的网站模板,在左上方有一个固定的标题,在左下方和右下方有一个固定的底线。

中间的内容应该居中,而我只是不太清楚自己在做什么错。

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

问题2.)在html标签上声明了height: 100% ,为什么网站大于100%并延伸到浏览器窗口之外?

问题3.)为什么bottom-left显示正确,而bottom-right显示不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.)如果删除高度:100%css属性,为什么垂直居中不起作用?

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

问题2.)在html标签上声明了height:100%时,为什么网站大于100%并延伸到浏览器窗口之外?

仅此一项就不会超出页面范围。 但是,如果您向100%元素添加页边距,边框或类似属性,则除了 100%元素外还会添加这些元素,从而使元素延伸到窗口边缘之外。

问题3.)为什么左下角显示正确,而右下角显示不正确?

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

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

暂无
暂无

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

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