将div放在包装上居中(当它不合适时) [英] Center div on wrapping (when it doesn't fit on the line)

查看:122
本文介绍了将div放在包装上居中(当它不合适时)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图仅使用CSS创建此布局:

I am trying to create this layout using only CSS:

标题合适时:

标题不匹配时:

如果右侧的btn换行,则应居中.

The btn on the right should be centered if it wraps.

我尝试过:

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

But obviously, the btn is still on the right after it wraps. Any idea how to center it when it wraps ? And I'd like to avoid javascript.

在这里拨弄: http://jsfiddle.net/b7rvhwqg/

推荐答案

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

此处更新了示例

技巧是将justify-content: center/flex-wrap: wrap添加到父.container元素以进行水平居中.然后,将第一个元素的margin-right值调整为auto,以防止最后一个元素在同一行上时居中.

The trick is to add justify-content: center/flex-wrap: wrap to the parent .container element for horizontal centering. Then adjust the first element's margin-right value to auto in order to prevent the last element from being centered when it's on the same line.

(您可能需要调整浏览器的大小以查看其调整方式.)

(You may need to resize the browser to see how it adjusts).

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

这篇关于将div放在包装上居中(当它不合适时)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆