代码之家  ›  专栏  ›  技术社区  ›  GetFree

如何在没有工作台的情况下实现工作台的对中功能

  •  4
  • GetFree  · 技术社区  · 14 年前

    对我来说 table 是指它们的宽度根据其内容进行调整。

    <table align=center style="border: 1px solid black">
    <tr><td style="padding: 20px">
    some text here
    </table>
    

    通过使用 float CSS属性,即它们的宽度根据其内容进行调整。但元素不会居中。

    那么,问题是:如何将块元素居中,并使该元素以跨浏览器的方式调整其宽度以适应其内容?

    5 回复  |  直到 13 年前
        1
  •  1
  •   meder omuraliev    14 年前

    display:table IE的解决方法是使用父元素和文本-align:center on 一 inline/inline-block

    <div id="for-ie">
    <div id="el">whatup son</div>
    </div>
    
    <style>
    #el { 
    display:table;
    margin:0 auto;
    }
    
    /* for IE, throw this in a CC */
    #for-ie { text-align:center; }
    #el { 
    zoom:1;
    display:inline;
    }
    </style>
    

    Demo

    下面是我写的关于这个主题的快速教程: http://work.arounds.org/centering-block-level-element-variable-width/

    我不困的时候就把它拉长。

        2
  •  1
  •   Community leo1    4 年前

    CSS: The Definitive Guide 通过 Eric Meyer

    如果两个边距都设置为“自动”,如下面的代码所示,则它们的长度将相等,从而使元素在其父元素中居中:

    p {width: 100px; margin-left: auto; margin-right: auto;}
    

    将两个边距设置为相等长度是使元素居中的正确方法,而不是使用文本对齐(文本对齐仅适用于块级元素的内联内容,因此将元素设置为文本居中对齐不应使其居中。)

    实际上,只有1999年2月之后发布的浏览器才能正确处理自动边距居中,而且并非所有浏览器都完全正确。那些不能正确处理自动页边距的浏览器的行为方式不一致,但最保险的做法是假设过时的浏览器会将两个页边距都重置为零。

    然而,

    IE/Win-up-through-IE6中的一个更有害的bug是,它实际上处理文本对齐:将其作为元素居中,并将元素和文本一起居中。这在IE6和更高版本的标准模式中不会发生,但在IE5.x和更早版本中仍然存在。

        3
  •  1
  •   Arseni Mourzenko    14 年前

    如果您想在页面中间显示一些文本,可以使用以下方法:

    <div style="text-align:center;">
        <div style="background:red;display:inline;">
            Hello World!
        </div>
    </div>
    

    第一个块将内容与中间对齐。第二个将填充与其内容物相等的高度,因为 display:inline 将迫使 <div/> <span/> ,即根据内容而不是剩余空间调整其宽度。

    注意这仅限于单行文本(如“此处的某些文本”)。

        4
  •  0
  •   jcubic    14 年前

    使用此CSS

    #content {
      position: absolute;
      width: 150px;
      margin-left: -75px;
      left: 50%;
      border: 1px solid #000;
      text-align: center;
      padding: 20px;
    }
    

    这个html <div id=“content”> 这里有一些文字 </部门>

        5
  •  0
  •   ExtraNoise    14 年前

    天哪,莫莉小姐!这些答案实在太复杂了。

    div.centered {
     width:100%;
     margin:0 auto;
     text-align:center;
    }
    
    div.centered span {
     padding:20px;
     border:1px solid #000;
    }
    

    然后在你的身体里使用这个:

    <div class="centered"><span>Hello world!</span></div>