我正在使用The Odin Project學習CSS,並製作了Google.com主頁的樣機。一切看起來都很完美,直到我調整了瀏覽器窗口的大小和元素移動的位置。如何在調整網頁大小時保持div居中?
我一直在嘗試很多不同的方法,如何在頁面調整大小時保持div(Google徽標,搜索欄和按鈕)居中。
#header {
position: absolute;
top: 50%;
left: 50%;
margin-left: -150px;
margin-top: -125px;
width: 300px;
padding: 10px;
}
#topbar {
font-family: arial, sans-serif;
}
.centered {
width: 960px
}
.footer {
position: absolute;
right: 0;
bottom: 0;
left: 0;
padding: 0.15rem;
background-color: #f2f2f2;
font-family: arial, sans-serif;
font-size: 15px;
color: #666;
}
.alignleft {
float: left;
}
.alignright {
float: right;
}
p {
font-family: Arial, Helvetica, sans-serif;
font-size: 14px;
color: #7D7676;
}
<title>Google</title>
<link rel="stylesheet" type="text/css" href="google-homepage-css.css">
<!-- Top bar -->
<body>
<div id="topbar">
<p align="right"><a href="https://mail.google.com" style="color:#7D7676;text-decoration: none">Gmail</a> <a href="https://images.google.com" style="color:#7D7676;text-decoration: none">Images</a>
<img style="vertical-align:middle" src="http://i.imgur.com/xmMdSIp.png"> </p>
</div>
<br>
<!-- Google Center Image -->
<div id="centered">
<div id="logo">
<img id="header" src="http://i.imgur.com/hs6n5hR.png" width="400">
</div>
</div>
<!-- Search Bar and Buttons -->
<div id="search">
<form id="searchbar" width="500">
<br>
<input type="text">
<br>
</form>
<br>
<button type="button" id="firstbutton">Google Search</button>
<button type="button" id="secondbutton">I'm Feeling Lucky</button>
</div>
<!-- Footer -->
<div class="footer">
<p class="alignleft"><a href="https://www.google.com/intl/en/ads/" style="color:#666;text-decoration: none"> Advertising</a>
<p class="alignleft"><a href="https://www.google.com/services/" style="color:#666;text-decoration: none">Business</a>
<p class="alignleft"><a href="https://www.google.com/intl/en/about/" style="color:#666;text-decoration: none">About</a>
</p>
<p class="alignright"><a href="https://www.google.com/intl/en/policies/privacy/" style="color:#666;text-decoration: none">Privacy</a>
<a href="https://www.google.com/intl/en/policies/terms/" style="color:#666;text-decoration: none">Terms</a>
<a href="https://www.google.com/preferences" style="color:#666;text-decoration: none">Settings </a>
</p>
</div>
我覺得應該是這樣的,但我不知道:
div {
position: relative
margin-left:auto;
margin-right:auto;
}
注意:我將在搜索欄和按鈕之後調整大小和添加顏色,這是我在瀏覽器頁面重新調整大小時,如何將搜索欄和按鈕保持在Google徽標下居中的最大擔憂。
你試過嗎? ''''' –
無論屏幕大小如何,google徽標都居中。複製你爲此做的任何事情? – imjared
您可以將margin-left/margin-right設置爲「auto」,但您需要指定div的寬度以允許broawser計算邊距。 – Dexter0015