[英]How can I horizontally center two columns of list items(with or without Bootstrap)?
[英]How to center content horizontally without overlapping items on the side
我正在尝试创建一个类似于iOS的UINavigationBar的视图布局:
UINavigationBar的标题以屏幕为中心,两侧都有可选的导航项(按钮)。 如果标题太宽而不适合中心,那么它将被推到一边以避免重叠导航项。
没有 JavaScript,这样的布局是否可以在CSS中使用?
这是我创建的一个小提琴 ,试图实现这种布局。
在上面的屏幕截图中,通过浮动两侧的红色和蓝色按钮,并将黄色div的左右边距设置为auto
来实现布局。 上面的第二行正是我想要的,但不幸的是我必须在黄色div上设置一个显式宽度。
我也尝试过flexbox,但它不允许我将黄色div放在容器中心。
如果在这种情况下无法避免使用JavaScript,那么实现它的最佳方式(与每个浏览器最兼容)是什么?
使用绝对定位放置左/右列。
.left,
.right {
position: absolute;
}
.left {
left: 0;
}
.right {
right: 0;
}
.center {
padding: 0 200px; // Add indents so columns don't overlap its content.
}
.row { border: 1px solid black; position: relative; margin: 20px 0; padding: 5px 0; } .left, .right { position: absolute; } .left { background-color: red; width: 200px; left: 0; } .right { background-color: cyan; right: 0; } .center { margin: 0 auto; background-color: yellow; text-align: center; white-space: nowrap; padding: 0 200px; } .fixed { width: 130px; } .zero { width: 0px; }
<div class="row"> <div class="left">left</div> <div class="right">right</div> <div class="center">center center center</div> </div> <div class="row"> <div class="left">left</div> <div class="right">right</div> <div class="center">center center center</div> </div> <div class="row"> <div class="left">left</div> <div class="right">right</div> <div class="center">center center center</div> </div>
您可以使用position: absolute
来精确地row
的中间实现center
div,而不管左右的位置。
此外,提供position: relative
对于left
和right
具有更高的z-index
,以使它们出现在center
上方。
参考代码:
.row { border: 1px solid black; margin: 20px 0; padding: 5px 0; position: relative; height: 18px; } .left { float: left; background-color: red; width: 200px; position: relative; z-index: 2; } .right { float: right; background-color: cyan; position: relative; z-index: 2; } .center { margin: 0 auto; background-color: yellow; text-align: center; white-space: nowrap; } .absolute { position: absolute; left: 0; right: 0; } .zero { width: 0px; } @media only screen and (max-width: 565px) { .absolute { left: 200px; padding-left: 20px; text-align: left; } }
<div class="row"> <div class="left">left</div> <div class="right">right</div> <div class="center">center center center</div> </div> <div class="row"> <div class="left">left</div> <div class="right">right</div> <div class="center absolute">center center center</div> </div> <div class="row"> <div class="left">left</div> <div class="right">right</div> <div class="center zero">center center center</div> </div>
将浮动更改为绝对定位,将“行”作为其“锚点”
.row{
position: relative
}
.left,
.right {
position: absolute;
}
.left {
left: 0;
}
.right {
right: 0;
}
你可以将这些属性赋予黄色div:
position: absolute;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.