html - 无论内容如何,​​如何始终将容器水平和垂直居中

标签 html css centering

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

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

        <!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>

最佳答案

.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

关于html - 无论内容如何,​​如何始终将容器水平和垂直居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19261139/

相关文章:

javascript - 如何将 CSS 应用于 v15 中 React 渲染的数组?

jquery - 绝对元素 jQuery 居中问题

html - CSS:防止在不透明元​​素中叠加颜色

html - 绝对根 url css

python - Flask 请求问题

javascript - 如何为一台 Accordion 制作多个切换开关?

css - 如何在 Windows 边栏小工具中启用滚动条?

css - 如何使用页面中心作为引用来对齐 div 元素?

css - CSS 中类似表格的图像网格(但有一个扭曲)

html - 如何阻止 flex 拉伸(stretch)到 100% 宽度?