Reputation: 2166
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.
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?
A fiddle showing basically what I'm looking for: https://jsfiddle.net/5bvmnt3j/
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.
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))
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>
Upvotes: 2
Views: 1207
Reputation: 345
You can do this with a media query if the buttons have a fixed width.
https://jsfiddle.net/jaxon58/c0Lsrb7o/3/
.wrapper {
text-align: center;
}
button {
width: 200px;
display: inline-block;
}
@media(min-width: 420px) {
.wrapper {
text-align: left;
}
}
<div class="wrapper">
<button>Btn #1</button>
<button>Btn #2</button>
</div>
You will need to tweak the media query and the button widths to get them exact.
Upvotes: 2
Reputation: 371361
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>
Upvotes: 4