[英]Vertically aligning span inside fixed positioned div
我知道,之前有关于这方面的帖子,但是我已经查看了所有这些帖子,但似乎仍然无法使其工作。 我见过的大多数相关答案都要求你指定包含div的高度,在我的例子中是动态的。
我在窗口底部有一个固定的div。 我希望在右侧有一个关闭按钮,并且无论高度如何,总是在div的中心垂直对齐。
JSfiddle: https ://jsfiddle.net/w2zd3q0b/1/
.bottombar { width: 100%; position: fixed; left: 0; bottom: 0; z-index: 9990; border: 1px solid #000; padding: 0.5em; } .bottombar p { /* Leave room for the dismiss button */ margin: 0 1.5em 0 0; padding: 0; } .dismiss { position: absolute; right: 1.5em; cursor: pointer; }
<div class="bottombar"> <p>This is some message inside of a div. I want to vertically center align the span. This is some message inside of a div. I want to vertically center align the span.<span class="dismiss">X</span></p> </div><!--/.bottombar -->
在这种情况下,它看起来很好,直bottombar
div占用多行文本,然后跨度不再垂直居中。
您可以使用适用于未知高度容器的CSS3 transform
。
.dismiss {
position: absolute;
top: 50%;
transform: translateY(-50%);
...
}
.bottombar { width: 100%; position: fixed; left: 0; bottom: 0; z-index: 9990; border: 1px solid #000; padding: 0.5em; box-sizing: border-box; } .bottombar p { margin: 0 1.5em 0 0; padding: 0; } .dismiss { position: absolute; top: 50%; transform: translateY(-50%); right: .5em; cursor: pointer; }
<div class="bottombar"> <p>This is some message inside of a div. I want to vertically center align the span. This is some message inside of a div. I want to vertically center align the span. <span class="dismiss">X</span></p> </div>
我还在代码片段中为div添加了box-sizing
,以便为您提供真正的100%宽度(包括边框),您可能需要稍微调整相关间距。
所以我清理了一些东西,并使用flexbox
以简单的样式flexbox
(更多信息在这里 )
.bottombar {
width:100%;
position: fixed;
left: 0;
bottom: 0;
z-index: 9990;
border: 1px solid #000;
/* padding: 0.5em; */
display: flex;
align-items: center;
}
.bottombar>span {
padding: 0.5em;
}
.bottombar .message{
flex-grow: 1;
}
.dismiss {
cursor: pointer;
}
HTML
<div class="bottombar">
<span class='message'>
This is some message inside of a div. I want to vertically center align the span.
</span>
<span class="dismiss">X</span>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.