如何让DIV和table和网页居中显示

如题所述

代码:


效果:


源代码:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
</head>
<style>
div{border:#0000CC 1px solid;width:50px; height:50px;}
table{border:#0000CC 1px solid;width:50px; height:50px;}
</style>

<body>
  <div style="margin:0 auto;"></div>
<br />
  <table style="margin:0 auto"></table>
</body>
</html>


原理:

margin:0 auto;0代码的是距离上下边界为0,auto代表距离左右边界为自适应,也就是居中。

温馨提示:内容为网友见解,仅供参考
第1个回答  2016-12-08
DIV和table和网页居中显示其实有很多种方法的,但目前的话我只会以下三种 ,所以你可以先试试。那么分别是那三种呢?下面就来看一看吧。
【方法一】:
这个方法把一些 div 的显示方式设置为表格,因此我们可以使用表格的 vertical-align property 属性。
<div id="wrapper">
<div id="cell">
<div class="content">
Content goes here</div>
</div>
</div>
#wrapper {display:table;}
#cell {display:table-cell; vertical-align:middle;}
优点:
content 可以动态改变高度(不需在 CSS 中定义)。当 wrapper 里没有足够空间时, content 不会被截断
缺点:
Internet Explorer(甚至 IE8 beta)中无效,许多嵌套标签(其实没那么糟糕,另一个专题)
【方法二】:
这个方法使用绝对定位的 div,把它的 top 设置为 50%,top margin 设置为负的 content 高度。这意味着对象必须在 CSS 中指定固定的高度。
因为有固定高度,或许你想给 content 指定 overflow:auto,这样如果 content 太多的话,就会出现滚动条,以免content 溢出。
<div class="content">
Content goes here</div>
#content {
position:absolute;
top:50%;
height:240px;
margin-top:-120px; /* negative half of the height */
}

适用于所有浏览器
不需要嵌套标签
缺点:
没有足够空间时,content 会消失(类似div 在 body 内,当用户缩小浏览器窗口,滚动条不出现的情况)
【方法三】:
这种方法,在 content 元素外插入一个 div。设置此 div height:50%; margin-bottom:-contentheight;。
content 清除浮动,并显示在中间。
<div id="floater">
<div id="content">
Content here</div>
</div>
#floater {float:left; height:50%; margin-bottom:-120px;}
#content {clear:both; height:240px; position:relative;}
优点:
适用于所有浏览器
没有足够空间时(例如:窗口缩小) content 不会被截断,滚动条出现
第2个回答  2016-11-29
可以再DIV和table的样式中加入 margin:0 auto,div必须有宽和高才会生效
第3个回答  2016-12-25
<center>html代码</center>
这样就可以实现代码居中
相似回答