【发布时间】:2019-06-12 21:37:52
【问题描述】:
如何仅使用 CSS 将 div 垂直和水平放置在浏览器中心?
确保它也适用于 IE7。
如果一切都失败了,我们可能会使用 JavaScript,但这是最后的选择。
【问题讨论】:
如何仅使用 CSS 将 div 垂直和水平放置在浏览器中心?
确保它也适用于 IE7。
如果一切都失败了,我们可能会使用 JavaScript,但这是最后的选择。
【问题讨论】:
HTML:
<div id="something">... content ...</div>
CSS:
#something {
position: absolute;
height: 200px;
width: 400px;
margin: -100px 0 0 -200px;
top: 50%;
left: 50%;
}
【讨论】:
最简单的解决方案就是使用自动边距,并为您的 div 提供固定的宽度和高度。这将适用于 IE7、FF、Opera、Safari 和 Chrome:
HTML:
<body>
<div class="centered">...</div>
</body>
CSS:
body { width: 100%; height: 100%; margin: 0px; padding: 0px; }
.centered
{
margin: auto;
width: 400px;
height: 200px;
}
编辑!!抱歉,我刚刚注意到你说的是垂直的……顶部和底部的默认“自动”边距为零……所以这只会水平居中。垂直和水平定位的唯一解决方案是像接受的答案一样使用负边距。
【讨论】:
margin: auto;
【讨论】:
试试这个
#center_div
{
margin: auto;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
【讨论】:
使用这个:
center-div { margin: auto; position: absolute; top: 50%; left: 50%; bottom: 0; right: 0; transform: translate(-50% -50%); }
【讨论】:
您还可以使用以下内容设置您的 div:
#something {width: 400px; margin: auto;}
使用该设置,div 将具有设置的宽度,并且边距和任一边将根据浏览器的大小自动设置。
【讨论】:
<html>
<head>
<style>
*
{
margin:0;
padding:0;
}
html, body
{
height:100%;
}
#distance
{
width:1px;
height:50%;
margin-bottom:-300px;
float:left;
}
#something
{
position:relative;
margin:0 auto;
text-align:left;
clear:left;
width:800px;
min-height:600px;
height:auto;
border: solid 1px #993333;
z-index: 0;
}
/* for Internet Explorer */
* html #something{
height: 600px;
}
</style>
</head>
<body>
<div id="distance"></div>
<div id="something">
</div>
</body>
</html>
在 FF2-3、IE6-7、Opera 中测试,运行良好!
【讨论】:
.center {
margin: auto;
margin-top: 15vh;
}
应该做的伎俩
【讨论】:
<center>
<h3 > your div goes here!</h3>
</center>
【讨论】:
<center> 是 HTML,而不是 CSS。它水平居中文本而不是垂直居中。
<center> 元素是obsolete。相反,请使用 CSS 中的 text-align 属性。
对于旧版浏览器,您需要在 HTML doc 顶部添加这一行
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
【讨论】: