簡體   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