仅在包装上居中按钮 [英] Center buttons on wrap only

查看:41
本文介绍了仅在包装上居中按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种方法可以仅使用CSS来做到这一点,但到目前为止我还没有真正找到任何东西.

I'm wondering if there is a way to do this with just CSS but so far I haven't really found anything.

在响应式容器中,我有几个按钮彼此串联.

I have a few buttons that sit inline with each other inside of a responsive container.

但是,当它们环绕并且第二个按钮下降到新行时,我想将它们居中.有人知道仅靠CSS就能做到吗?

However, when they wrap, and the 2nd button drops to a new line, I would like to then center them. Anyone know if this is possible with just css?

基本上显示我在寻找什么的小提琴: https://jsfiddle.net/5bvmnt3j/

A fiddle showing basically what I'm looking for: https://jsfiddle.net/5bvmnt3j/

在小提琴中,假装包装器是响应式的,并且随着浏览器宽度的变化并使按钮包装,我们得到的是我在wrapper2类中显示的布局,而不是在原始包装器类中看到的布局.

In the fiddle pretend the wrapper is responsive and as the browser width changes, and makes the buttons wrap, we get the layout I'm showing in the wrapper2 class instead of what is seen in the original wrapper class.

我知道通常情况下,仅使用CSS的解决方案并不是真正希望看到的东西,但是使用Flexbox我已经看到了一些非常酷的东西,类似于我的要求.(例如,将div居中包装(当它不适合行))

I know normally this isn't really something you would expect to see with a css only solution but I've seen some pretty cool things with flexbox similar to what I'm asking. (e.g. Center div on wrapping (when it doesn't fit on the line))

希望避免使用JS来检测高度变化,然后切换类.谢谢.

Hoping to avoid using JS to detect a height change and then toggling a class. Thx.

.wrapper {
  background: red;
  width: 300px;
}
.wrapper2 {
  background: blue;
  margin-top: 30px;
  text-align: center;
  width: 150px;
}
button {
  width: 100px;
}

<div class="wrapper">
  <button>Btn #1</button>
  <button>Btn #2</button>
</div>

<div class="wrapper2">
  <button>Btn #1</button>
  <button>Btn #2</button>
</div>

推荐答案

您可以使用flexbox和媒体查询来做到这一点:

You can do it with flexbox and a media query:

.wrapper {
  display: flex;
  background: red;
  width: 500px;
}
button {
  margin: 5px;
  padding: 5px;
  width: 100px;
}
@media ( max-width: 700px ) {
  .wrapper { flex-direction: column; align-items: center; }
}

<div class="wrapper">
  <button>Btn #1</button>
  <button>Btn #2</button>
</div>

这篇关于仅在包装上居中按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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