0

无论内容如何,​​如何始终将容器水平和垂直居中?下面是我正在尝试做的一个基本示例。

这种方法是否正确,或者我的问题有更简单的解决方案吗?

        <!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" lang="en" xml:lang="en">
        <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <title>3 columns</title>


        <style>
        div.container { 
            height: 200px;
            width: 100%;
            margin-left: auto;
            margin-right: auto;
            margin-top: 25%;
            margin-bottom: 20%;  
        }

        div.col {
            float: left;
            width: 25%;

        }
        </style>

        </head>
        <body>

        <div class="container">
            <div class="col" align="center">This is col 1</div>
            <div class="col" align="center">This is col 2</div>
            <div class="col" align="center">This is col3</div>
        </div>


        </body>
        </html>
4

2 回答 2

1
.container {
  position: absolute;
  left: 50%;
  top: 50%;

  /*
  Nope =(
  margin-left: -25%;
  margin-top: -25%;
  */

  /* 
  Yep!
  */
  -webkit-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);

  /*
  Not even necessary really. 
  e.g. Height could be left out!
  */
  width: 40%;
  height: 50%;
}

来源:http ://css-tricks.com/centering-percentage-widthheight-elements/

请注意,在transform撰写本文时,该属性将需要某些浏览器的前缀 ( -ms, -webkit)。 http://caniuse.com/transforms2d

于 2013-10-09T00:58:12.150 回答
0

正如 Niels Keurentjes 所说……table-cell是个不错的小提琴

html:

<div class="outer">
    <span class="inner">
        <img src="http://www.google.co.in/trends/resources/2327917647-google-icon.png"/>
    </span>
</div>
<div class="outer">
    <span class="inner">
        <span class="innerinner">blah blah blah blah blah blah blah blah blah blah</span>
    </span>
</div>

CSS:

.outer{
    width:300px;
    height:200px;
    border:1px solid blue;
    display:table;
    text-align:center;
}

.inner{
    display:table-cell;
    vertical-align:middle;
    border:1px solid red;
}
.inner img{
    border:1px solid orange;
}
.innerinner{
    border:1px solid red;
}
于 2013-10-09T01:47:56.723 回答