[英]Vertically centering an inline-block element
我正在尝试设计一个Flash消息弹出窗口,其样式类似于StackOverflow本身使用的弹出窗口-
他们通过将消息浮动到左侧并将关闭按钮浮动到右侧来实现此目的。 如图所示,它们还通过将固定按钮margin-top
留在margin-top
,使“关闭”按钮垂直“居中”。
我的即显消息略有不同,因为消息居中。
在较高的层次上,我采用以下方法:
<div>
,显示为行inline-block
margin-left
。 float: right
因为我知道将float: right
元素垂直居中存在一些困难 。 如上图所示,最困难的时间是使关闭按钮垂直居中。 它只是拥抱底部。
我的HTML和CSS在下面-有没有简单的方法可以做到这一点?
谢谢!
<div id="flash" class="center active error">
<div class="flash-message">
Please enter an email. Please enter an email. Please enter an email. Please enter an email. Please enter an email. Please enter an email.
</div>
<div class="flash-close">x</div>
</div>
// Flash messages
#flash {
// Display it as an offset from the parent <body> tag
position: absolute;
display: block;
top: 4em;
left: 0;
right: 0;
// Center it on the page
width: 50%;
text-align: center;
z-index: 101;
line-height: 2.5;
overflow: hidden;
// Cool shadows
-webkit-box-shadow: 0 0 5px $black;
-moz-box-shadow: 0 0 5px $black;
box-shadow: 0 0 5px $black;
border-radius: 3px;
// Set color based on message type
&.error { background: $mustard; }
&.notice { background: $light-green; }
.flash-message {
display: inline-block;
width: 80%;
padding-left: (100% - 80%)/2;
// Give it 3px on the top and bottom for some space
margin: 3px 0;
}
.flash-close {
display: inline-block;
// This doesn't seem to do anything.... -_-
// I've also tried auto-setting margins, and making it `position: relative`
// so I can set top/bottom as 50%
vertical-align: middle;
// Give it 3px on the top and bottom for some space
// Also 11px from the right edge
margin: 3px 11px 3px 0;
// Styling the "X" and the box around it
padding: 2px 6px;
font-family: Arial, sans-serif;
font-size: 1em;
font-weight: normal;
color: $white;
line-height: 1;
border: 1px solid rgba(255,255,255,0.2);
}
}
您可以尝试使用flexbox居中。
#flash {
display: flex;
align-items: center;
justify-content: center;
}
附加信息: Flexbox
只是玩弄您的代码,您需要在CSS中添加以下内容:
看看这个https://jsfiddle.net/max234435/tjhb3md8/-我认为您正在寻找的工作版本
float: right; display: table-cell;
这是一个工作的小提琴: https : //jsfiddle.net/code4pi/yyrko1zw/
在较新的浏览器中,可以使用display flex属性。
只需将以下内容添加到您现有的类中:
#flash {
display: flex;
justify-content: center;
}
.flash-close {
align-self: center;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.