html - 在包装上居中 div(当它不适合该行时)

标签 html css centering word-wrap

我正在尝试仅使用 CSS 创建此布局:

当标题适合时:

sketch 1

当标题不合适时:

sketch 2

如果换行,右边的 btn 应该居中。


我试过这个:

.container {
    width: 100%;
    border: 1px solid grey;
    padding: 5px;
}
.block {
    padding: 5px;
    border: 1px solid orange;
    float: left;
}
.right-block {
    float: right;
}
<div class="container">
    <div class="block">Logo</div>
    <div class="block">Title that is too long</div>
    <div class="block right-block">right-btn</div>
    <div style="clear: both"></div>
</div>

但很明显,btn 换行后仍然在右边。知道如何在包装时将其居中吗?我想避免使用 javascript。

在这里 fiddle :http://jsfiddle.net/b7rvhwqg/

最佳答案

使用 flexbox 布局的纯 CSS 解决方案:

Updated Example Here

诀窍是将justify-content: center/flex-wrap: wrap 添加到父级.container 元素以实现水平居中。然后将第一个元素的 margin-right 值调整为 auto 以防止最后一个元素在同一行时居中。

(您可能需要调整浏览器大小以查看其调整情况)。

.container {
  width: 100%;
  border: 1px solid grey;
  padding: 5px;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}
.logo-text {
  display: flex;
  margin-right: auto;
}
.block {
  padding: 5px;
  border: 1px solid orange;
}
.center-block {
  white-space: nowrap;
  margin-right: auto;
}
<div class="container">
  <div class="logo-text">
    <div class="block logo">Logo</div>
    <div class="block text">This title is short.</div>
  </div>
  <div class="block right-block">right-btn</div>
</div>
<div class="container">
  <div class="logo-text">
    <div class="block logo">Logo</div>
    <div class="block text">This title is slightly longer than the other one. This title is longer than the other one...</div>
  </div>
  <div class="block right-block">right-btn</div>
</div>

关于html - 在包装上居中 div(当它不适合该行时),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33877327/

相关文章:

javascript - 网页适合分辨率

html - 仅使用 css 为输入字段切换标签样式(事件/焦点)

html - CSS/表格 : how to put two versions of a text side-by-side?

html - <a> 水平对齐稍微偏离中心

Css 翻译和居中元素

html - 当使用 `diplay: table;` 将内容居中时,如何使填充按浏览器的宽度缩放?

javascript - 在 Flowplayer 中禁用加载屏幕

javascript - 如何将文字放入圆圈内

javascript - 如何在 Python 中使用 Appengine 读写文件?

html - 加载新元素时为元素添加动画