之前设计网页,如果希望div或table居中,总是用<center></center>把它包起来,但是这样的结果,div或table虽然居中了,但div或table里面的文字也居中了,这是不符合设计者意愿的。那么,我们能否用css实现div或table居中,文字不居中呢?答案是肯定的,本文将给你介绍如何实现此效果。
css实现div或table居中 文字不居中
首先,介绍css的写法。
.countainer{ margin:auto; width:600px; height:100px; background-color:#cccccc; }
这里我们要注意一个关键代码,就是 margin:auto; ,这个代码就是起到可以让div或table居中,而文字不居中的功效。
了解这个后,剩下的,就是html中div或table引用此类 .countainer 了,看看下面的实例。
div代码:
<div class="countainer"> div居中, 而里面的文字不居中 </div>
table代码:
<table class="countainer"> <tr> <td>table居中, 而里面的文字不居中</td> </tr> </table>
div或table使用类写法 class="countainer" ,代码并不复杂。
最后,附上完整的html代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>让div+css的div居中, 而里面的文字不居中的做法</title> <style type="text/css"> .countainer{ margin:auto; width:600px; height:100px; background-color:#cccccc; } </style> </head> <body> <div class="countainer"> div居中, 而里面的文字不居中 </div> <br> <table class="countainer"> <tr> <td>table居中, 而里面的文字不居中</td> </tr> </table> </body> </html>
margin:auto 可以让所有html元素居中
通过上述例子,看到 margin:auto 可以让div或table居中,其实,它可以让所有html元件居中,如:<p>、<pre>、<input>等元素。
发表评论