[英]How to vertically center a floating element of unknown height in Bootstrap?
相关的Bootply: http : //www.bootply.com/OdVIzrxTV5
我正在Bootstrap中创建一个布局,其中各节在移动设备上彼此叠放:
|---|
| A |
|---|
| B |
|---|
| C |
|---|
但在台式机上分开:
|---| |---|
| B | | A |
|---| |---|
| C |
|---|
我在A和C部分使用.pull-right
来完成这项工作,但是由于Bootstrap使用float,因此B部分会自动对齐顶部,如上所示。 我真正想要的是使B部分像这样垂直居中:
|---|
|---| | A |
| B | |---|
|---| | C |
|---|
B部分应相对于A和C垂直居中。 我尝试在行上应用flexbox,但这会破坏布局。 我还尝试了其他各种CSS hack,但似乎都无法以响应方式正确工作,从而破坏了移动或台式机的布局。
高度不明的垂直居中部分B是否有可靠的响应解决方案? 如果有帮助,则B部分将成为图像元素。
您还尝试了哪些其他CSS hack? 正如我所知道的那样,只是好奇而已,在使用Bootstrap的出厂版本(无sass / less)时,您确实必须对CSS选择器保持谨慎。
话虽这么说,也许JavaScript方法可能会有所帮助! 这是代码,我将带您逐步进行一些更改以满足您的需求。
可变breakpoint
将此变量更改为为断点设置的任何像素。 对于Bootstrap,默认情况下,xs选择器在768处启动。 如果您想在其他断点处执行操作,则可以添加多个断点并使用更多的if / else语句。
首先, if
这将在页面加载时触发,并立即测试屏幕的宽度,并在需要时更改边距。
window.resize()
每当调整窗口大小时,类似的if语句就会消失并重新计算边距。 如果您在其中添加一些文字并更改高度,则会看到其居中。 如果由于某种原因将浏览器的大小调整到了断点以下,则仅将边距更改为继承。
一些变化
您可能会注意到div略低于一半。 这可能只是关于jQuery如何检索高度的数学错误。 只需添加您要向上或向下编辑的任何常量。
// Where 20 is in pixels
var topMargin = (totalMargin / 2) - 20;
如果您想使左div居中,以便始终位于A和C部分之间,则只需更改topMargin
计算即可使用A div的高度。
如果您有任何疑问,请通知我!
$(document).ready(function() { var breakpoint = 768; if ($(window).width() > breakpoint) { var totalMargin = $(window).height() - $('#vertCenter').height(); var topMargin = totalMargin / 2; $('#vertCenter').css('margin-top', topMargin); } $(window).resize(function(){ if ($(window).width() > breakpoint) { var totalMargin = $(window).height() - $('#vertCenter').height(); var topMargin = totalMargin / 2; $('#vertCenter').css('margin-top', topMargin); } else { $('#vertCenter').css('margin-top', 'inherit'); } }); });
.section-a, .section-c { font-size: 2em; } .section-b { font-size: 4em; }
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <div class="container"> <div class="row"> <div class="test"></div> <div class="col-xs-12 col-sm-6 pull-right"> <div class="section-a well well-lg">A</div> </div> <div class="col-xs-12 col-sm-6"> <div id="vertCenter" class="section-b well well-lg">B</div> </div> <div class="col-xs-12 col-sm-6 pull-right"> <div class="section-c well well-lg">C</div> </div> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.