如何水平居中内容而不会在侧面重叠项目

时间:2017-02-23 10:38:07

标签: javascript html css

我正在尝试创建一个类似于iOS的UINavigationBar的视图布局:

UINavigationBar

UINavigationBar的标题以屏幕为中心,两侧都有可选的导航项(按钮)。如果标题太宽而不适合中心,那么它将被推到一边以避免重叠导航项目。

这样的布局是否可以单独使用CSS 而不用 JavaScript?

这是我创建的fiddle,尝试实现此布局。

Fiddle screenshot

在上面的屏幕截图中,通过浮动任一侧的红色和蓝色按钮,并将黄色div的左右边距设置为auto来实现布局。上面的第二行正是我想要的,但遗憾的是我必须在黄色div上设置一个明确的宽度。

我也尝试过flexbox,但它不允许我将黄色div放在容器中心。

如果在这种情况下无法避免使用JavaScript,那么实现它的最佳方式(与每个浏览器最兼容)是什么?

4 个答案:

答案 0 :(得分:1)

使用绝对定位放置左/右列。

.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>

答案 1 :(得分:0)

您可以使用center完全在row的中间实现position: absolute div,无论左侧和右侧的位置如何。右。

另外,position: relative提供left&amp; 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>

参考代码:

main
void method(int a,int b)

答案 2 :(得分:0)

将浮动更改为绝对定位, 用&#34; row&#34;作为他们的&#34;锚&#34;

.row{
 position: relative
}

.left,
.right {
  position: absolute;
}

.left {
  left: 0;
}

.right {
  right: 0;
}

答案 3 :(得分:-1)

你可以将这些属性赋予黄色div:

position: absolute;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;