Ming
Ming

Reputation: 784

Prevent margins from pushing elements out of container

I am having trouble fitting three inline-blocks (black) inside a container (gray) with fixed width. These blocks have margins (orange), and the problem is that the last block is pushed into the next row even though the actual element (black) is still inside its container (gray).

I want blocks to be pushed into the next line when the actual block is outside the container, not the margins. How can i do this?

Reference image: enter image description here

Edit: A workaround I found was to wrap the blocks into another container with enough width to cover the right margins.

Upvotes: 3

Views: 2710

Answers (3)

ralph.m
ralph.m

Reputation: 14345

You could put the margin on the left of each box instead, and then pull the box wrapper to the left with a negative margin. E.g. http://codepen.io/pageaffairs/pen/Hesgu

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
section {width: 60%; margin: 0 auto; background: #f7f7f7;}
article {margin-left: -20px;}
div {width: 200px; height: 100px; display: inline-block; margin-left: 20px; background: black;}

</style>
</head>
<body>
<section>
    <article>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
    </article>
</section>
</body>
</html>

Upvotes: 0

xzegga
xzegga

Reputation: 3139

You can use flexbox model instead inline-block, i include an example in jsfiddle with crossbrowser:

display: -webkit-box; /* OLD - iOS 6-, Safari 3.1-6 */
display: -moz-box; /* OLD - Firefox 19- (buggy but mostly works) */
display: -ms-flexbox; /* TWEENER - IE 10 */
display: -webkit-flex; /* NEW - Chrome */
display: flex; /* NEW, Spec - Opera 12.1, Firefox 20+ */

You can play with width of the stage to get a responsive results http://jsfiddle.net/X5pg7/

Upvotes: 1

Marc
Marc

Reputation: 571

UPDATED

Here is the improved fiddle: http://jsfiddle.net/CKQLE/3/

Few key styles here are:

text-align: justify; on the container to evenly distribute the elements within the containing element.

font-size: 0; to remove whitespace that comes with inline block elements.

And this block:

.container:after{
  content: "";
  width: 100%;
  display: inline-block;
}

to handle overflow of elements.

Upvotes: 1

Related Questions