div+css中文字居中问题 不指定

Category : CSS | Post on 2008/08/21 16:48 by 特蓝克斯 | Comments:0
      今天在DIV制作页面的过程中,碰到文字无法垂直居中的问题,明明vertical-align已经设置为center但是显示的时候,文字依然顶端对齐。
  那么如何解决呢?事实上是因为遗漏了line-height属性,没有设置行高,所以导致了文字无法垂直居中。
       以下为具体代码 :
      
<div style="text-align:center; vertical-align:middle; line-height:24px">文字居中</div>

  文中的text-align属性为文字水平设置,属性有center[居中]、inherit[继承父对象的属性]、justify[两端对齐]、left[左对齐]、right[右对齐]
  文中的vertical-align属性为文字垂直设置,属性有baseline[基线]、bottom[]、inherit[继承父对象的属性]、middle[中线对齐]、sub[下标]、super[上标]、text-bottom[文本地对齐]、text-top[文本顶对齐]、top[顶部],另外还可以设置百分比,如vertical-align:10%;
  最后还要设置line-height属性,没有行高,也就没有办法判断该行的中线位置是哪,自然也就无法使文字显示为垂直居中了
png图片有很好的品质。阴影效果也不会有杂边,很流畅。如果插入网页的话可以给网站内容增色不少!更重要的是在不增加图片容量大小的情况下提高了页面的图片的质量。对于有复杂背景,如:在有颜色过度背景上插入不规则边框的图片带来极大很便利!

但目前IE中对于插入的透明背景的.png的图片是不能正常显示的。IE会自动给".png"格式的图片加个灰色背景。

解决这个的方法是增加javascript。具体方法如下:

把下面的代码放在head区就可以解决问题了:


<script language="javascript">
function correctPNG()  
{
for(var i=0; i<document.images.length; i++)
{
  var img = document.images[i]
  var imgName = img.src.toUpperCase()
  if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
  {
   var imgID = (img.id) ? "id='" + img.id + "' " : ""
   var imgClass = (img.className) ? "class='" + img.className + "' " : ""
   var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
   var imgStyle = "display:inline-block;" + img.style.cssText  
   if (img.align == "left") imgStyle = "float:left;" + imgStyle
   if (img.align == "right") imgStyle = "float:right;" + imgStyle
   if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle  
   var strNewHTML = "<span " + imgID + imgClass + imgTitle
   + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
  + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
   + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"  
   img.outerHTML = strNewHTML
   i = i-1
  }
}
}
window.attachEvent("onload", correctPNG);
</script>
  

也可以把这段代码单独加在一张图片上:

<span style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='male.png',sizingMethod='scale');"></span>
分页: 1/1 第一页 1 最后页 [ 显示模式: 摘要 | 列表 ]