【问题标题】:Button vertically centers content but div does not按钮垂直居中内容,但 div 不
【发布时间】:2013-12-17 14:56:45
【问题描述】:

以下垂直居中内部div

HTML

<button class="outer">
    <div class="inner">
        Hello<br>World
    </div>
</button>

CSS

.outer {
    position: absolute;
    top: 25%;
    left: 25%;
    bottom: 25%;
    right: 25%;
    padding: 0;
    background: none;
    border: none;
    outline: dashed 1px black;
    font-family: sans-serif;
    font-size: 16px;
    text-align: center;
}

.inner {
   background: #ccc;
}

JSFiddle

但如果我使用div 而不是button 作为外部元素,

出于语义原因,我想要 div 而不是 button。

我需要将哪些 CSS 样式添加到 .outer 类以生成与按钮相同的垂直对齐样式?

我需要这个才能在 Chrome 和 FF 中工作。

【问题讨论】:

  • 我想看看你做了什么,如果你不介意的话,可能会是一个小提琴

标签: html css vertical-alignment


【解决方案1】:

这就是你需要的:链接:http://jsfiddle.net/WP8um/2/

或者,如果您不希望外部 div 上的边距,您可以使用 top,left,bottom,right 属性。 http://jsfiddle.net/WP8um/3/

CSS

.outer {
 display: inline;
 margin:25%; 
 background: none;
 outline: dashed 1px black;
 border: none;
 padding: 0;
 width: 200px;
 height:200px;
}


 .inner {
 background: #ccc;
 text-align:center;
 margin: 50% 0;
}

【讨论】:

  • 外部元素的大小固定为 200 x 200 像素。在我的示例中,外部元素的大小基于其父元素的大小。
  • 您可以使用基于父级大小的百分比。父母的大小是多少?
  • 在这种情况下,父级是body。比较你的 JSFiddle 和我的,你会发现大小不同(取决于窗口大小)。
  • Div 是块元素。当按钮是内联元素时,它需要一些大小。
  • 50% 的边距不起作用,因为它是从元素顶部获取的,所以 div 不会正确居中
猜你喜欢
  • 1970-01-01
  • 2014-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
  • 1970-01-01
  • 2017-07-29
相关资源
最近更新 更多