【发布时间】:2016-02-11 09:36:51
【问题描述】:
目标是使按钮在 div 中水平和垂直居中。水平已处理,但垂直对齐有问题。
从vertical-align 上的w3schools page 声明,使用middle 具有以下结果:
"元素放在父元素的中间"
在我的问题 (see jsFiddle here) 中,我已将父元素中按钮的 CSS(据我所知)设置为垂直对齐。
HTML:
<div id='titleSection'>
<div class='title-inner right quarter-width'>
<form action='destroy.php' method='POST'>
<button>Log Out</button>
</form>
</div>
<div class='title-inner left quarter-width'>
<!--nothing-->
</div>
<div class='title-inner center half-width'>
<h1 class='centered-text'>Title</h1>
</div>
</div>
CSS:
* {
font-family:'Arial', Arial, sans-serif;
padding: 0;
margin: 0;
}
h1 {
padding: 2.1vh 0;
font-size: 6vmin;
}
div#titleSection {
width: 100%;
height: 12vh;
border: 2.5px solid #ff0fff;
}
div.title-inner {
height: 100%;
text-align: center;
display:inline-block;
}
div.quarter-width { width: 25%; }
div.third-width { width: 33.3%; }
div.half-width { width: 50%; }
div.left {
float: left;
background-color: rgba(255, 0, 0, 0.5);
}
div.center {
float: center;
background-color: rgba(0, 255, 0, 0.5);
}
div.right {
float:right;
background-color: rgba(0, 0, 255, 0.5);
}
.title-inner button {
vertical-align: middle;
}
认为父元素是title-inner div 我错了吗?
我也尝试将 CSS 设置为:
.title-inner form { vertical-align: middle; }
无济于事。
回顾一下:jsFiddle 中显示的所有额外 CSS 和 html 只是为了最准确地了解我正在尝试做的事情 - 如果这是不必要的,我深表歉意,但我宁愿将其保留以避免忘记我在哪里。最终目标只是将 Log Out 按钮(垂直)居中在右侧(蓝色)div 中。
【问题讨论】:
-
一个建议,用 flexbox 制作你的结构......你会用更少的 css 规则和更多的灵活性来实现你想要的。 - css-tricks.com/snippets/css/a-guide-to-flexbox
-
除了 flexbox 在 IE
-
w3schools 的文档非常糟糕。请改用 Mozilla 开发网络 (MDN) 文档。 developer.mozilla.org/en-US/docs/Web/CSS/vertical-align 另请注意文档中的“vertical-align CSS 属性指定 inline 或 table-cell 框的垂直对齐方式。”所以除非你的元素是内联或表格单元格,vertical-align 不会做任何事情。
标签: html css button alignment vertical-alignment