简体   繁体   English

垂直和水平对齐div内的所有内容和元素

[英]Vertical and horizontal align all content and elements inside a div

I have a div with some content, in this case 2 buttons and a paragraph. 我有一个div有一些内容,在这种情况下2个按钮和一个段落。 I want to vertically and horizontally align all the elements and content inside that div by changing its CSS. 我想通过改变它的CSS来垂直和水平地对齐div中的所有元素和内容。 How can I do this? 我怎样才能做到这一点?

<style>
  .middle {
    What to type in here?
  }
</style>

<div class="middle">
  <p>Hello</p>
  <br />
  <input type="button" value="Button 1">
  <br />
  <input type="button" value="Button 2">
</div>

Change your html to this: 将您的HTML更改为:

<div class="middle">
    <div id='mydiv'>
       <p>Hello</p>
       <input type="button" value="Button 1" />
       <input type="button" value="Button 2" />
    </div>
</div>

And your CSS to 而你的CSS

.middle
{
padding: 0;
}

#mydiv
{
display: table;
margin: 0 auto;
}

#mydiv *
{
display: block;
}

input[type='button']
{
margin: 0;
}

Working fiddle: http://jsfiddle.net/n6522/1/ 工作小提琴: http//jsfiddle.net/n6522/1/

PS. PS。 The border and width is just to give you an idea. 边框和宽度只是为了给你一个想法。 You don't need to add the first block. 您不需要添加第一个块。

Check this style: 检查这种风格:

/* stretch them to window's height */
html, body {
    height:100%;
}

/* normalize them from default 8px to zero */
html, body, div, p {
    margin:0;
    padding:0;
}

/* vertical align */
 body {
    display:table;
    width:100%;
    overflow:auto;
}
.middle {
    display:table-cell;
    vertical-align:middle;
}

/* horizontal align */
.middle {
    text-align:center;
}

jsfiddle #1 jsfiddle#1

Alternatively you can put all your html code into some container div and stylize it instead of the body tag: 或者,您可以将所有html代码放入某个容器div并将其样式化而不是body标记:

jsfiddle #2 jsfiddle#2

For completeness' sake, the simplest style where the content of the .middle division is centered and the height of the .middle also depends on its inner content can be made with the equal top and bottom paddings as follows: 为完整起见,其中的内容的最简单的样式.middle除法居中和高度.middle还取决于其内的内容可以与等于顶部和底部内边距被制备如下:

.middle {
    padding:5em 0;
    text-align:center;
}

jsfiddle #3 jsfiddle#3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM