【问题标题】:After aligning a div horizontally and vertically center将 div 水平和垂直居中对齐后
【发布时间】:2016-09-15 20:07:26
【问题描述】:

我看到很多问题如何将 div 水平和垂直居中对齐,我也得到了答案。

我得到的代码: html-

<div class="outer">
   <div class="middle">
      <div class="inner">
         <div align="center">
            <h1>The Content</h1>

            <p>Once upon a midnight dreary...</p>
         </div>
      </div>
   </div>
</div>

CSS-

.outer {
   display: table;
   position: absolute;
   height: 100%;
   width: 100%;
}

.middle {
   display: table-cell;
   vertical-align: middle;
}

.inner {
   margin-left: auto;
   margin-right: auto;
   background: blue; /*gave blue to know the height and width*/ 
}

我猜对了。
但我无法为其提供默认高度。

当我将 width: 50%;height: 50%; 提供给 class="inner" 时,仅接受宽度。
我什至无法在顶部和底部之间提供填充空间。
请帮忙。
请不要给我另一个代码来将 div 垂直和水平居中对齐

【问题讨论】:

  • 你能给小提琴吗?
  • 你可以给出一些像素的高度。

标签: html css


【解决方案1】:

你想要什么(我认为),这是:

body {
    margin : 0;
}

.outer {
   display: table;
   position: absolute;
   height: 100%;
   width: 100%;
}

.middle {
   display: table-cell;
   vertical-align: middle;
   text-align: center;
}

.inner {
   display: inline-block;
   width: 50%;
   height: 50%;
   background: blue;
}
<div class="outer">
   <div class="middle">
      <div class="inner">
          <h1>The Content</h1>
          <p>Once upon a midnight dreary...</p>
      </div>
   </div>
</div>

另见this Fiddle

【讨论】:

    【解决方案2】:

    您没有在正确的位置分配高度:50%。

    50% 占内部 div 的一半。您需要做的是为“内部”类中的 div 分配。

    你可以试试弹性盒子。

    添加此代码:

    .inner {
       margin-left: auto;
       margin-right: auto;
       background: blue;
       height: 50%; 
       width:50%;
        display: flex;
      flex-direction: column;
      justify-content: center;
    }
    

    查看https://jsfiddle.net/ke5z9ukh/1/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-23
      • 2013-11-25
      • 1970-01-01
      • 2015-08-29
      • 1970-01-01
      • 2011-04-26
      相关资源
      最近更新 更多