Reputation: 33956
I'm trying to figure out how to do this, basically I have two elements.
<div class="button">This is the first one</div>
<div class="button">This is the second one</div>
Sometimes both fit next to each other, in which case I'm ok with their styling.
However if the second one "falls down" due to the parent being too narrow I don't want the two elements to touch each other.
My problem is that adding a bottom-margin to the elements would also affect Case 1 (when they are next to each other) which I don't want to do. How can I separate the two elements when one is below the other?
Jsfiddle (try expanding and shrinking the result box)
Upvotes: 3
Views: 4135
Reputation: 16777
A very simple solution would be using negative padding
values, but since it's impossible, we can use another simple way, even though it's a bit of a walk around. You can wrap the container with another wrapping element, and give the container a negative margin-top
value.
HTML:
<div class="wrapper">
<div class="container">
<div class="button">This is the first button</div>
<div class="button">This is the second button</div>
</div>
</div>
CSS:
.wrapper {
overflow: hidden;
}
.container {
margin-top: -10px;
}
.button {
margin-right: 10px;
margin-top: 10px;
}
Upvotes: 3
Reputation: 29
I am not sure if there is a better way to do it with CSS, but if nothing else works, an invisible element below the first element could work? I'm not sure what your situation is, but there may be other options if you give us more details.
Upvotes: 0
Reputation: 425
This can be achieved by using media queries http://css-tricks.com/css-media-queries/. Basically you can control which rules be applied when the viewport falls below or above certain widths. I have forked your code to add a media query based on a viewport of 520px wide, however you can adjust however you want.
Find the code here (CSS):
.background{
background: red;
display: inline-block;
}
.button{
background: orange;
padding: 10px;
display: inline-block;
margin-right: 10px;
width: 200px;
}
@media all and (max-width: 520px){
.button{
margin: 0 0 10px 0;
}
.background{
width: 220px;
}
}
and HTML:
<div class="background">
<div class="button">This is the first button</div>
<div class="button">This is the second button</div>
</div>
Forked fiddle can be found here: http://jsfiddle.net/vsYpe/1/
Hope this helps!!!
Upvotes: 0
Reputation: 1638
This probably doesn't help much, but I would either make sure that the buttons only fall below one another in case of different screen width (in which case I could address this through @media queries) or add some top/bottom margin and make other elements supplement that.
Upvotes: 0