petko_stankoski
petko_stankoski

Reputation: 10713

Set space between divs

I have two divs like this:

<section id="main">
  <div id="left">
    <asp:ContentPlaceHolder ID="left" runat="server" />
  </div>
  <div id="right">
    <asp:ContentPlaceHolder ID="right" runat="server" />
  </div>
</section>

And here is my css:

#left {
  float: left;
  margin-right: 17px;    
}

#right {
  float: right;
}

I want the space between the divs to be 40px. I tried adding padding, margin and width in my css, but I think it didn't set the padding to correct 40px. How to do it?

Upvotes: 38

Views: 233116

Answers (4)

zawhtut
zawhtut

Reputation: 8541

You need a gutter between two div gutter can be made as following

margin(gutter) = width - gutter size
E.g margin = calc(70% - 2em)

    body{
        font-size: 10px;
    }
    
    #main div{
        float: left;
        background-color:#ffffff;
        width: calc(50% - 1.5em);
        margin-left: 1.5em;
    }
    <body bgcolor="gray">
    <section id="main">
            <div id="left">
                Something here     
            </div>
            <div id="right">
                    Someone there
            </div>
    </section>
    </body>

Upvotes: 2

the_spectator
the_spectator

Reputation: 1603

Another solution for spacing between N divs can be:

div + div {
  margin-left: 40px;
}

We are leveraging + css selector. It only selects the <div> elements that are placed immediately after <div> elements.

Notice: we are setting margin-left not margin-right here.

Upvotes: 7

David Salamon
David Salamon

Reputation: 2451

For folks searching for solution to set spacing between N divs, here is another approach using pseudo selectors:

div:not(:last-child) {
  margin-right: 40px;
}

You can also combine child pseudo selectors:

div:not(:first-child):not(:last-child) {
  margin-left: 20px;
  margin-right: 20px;
}

Upvotes: 66

benni_mac_b
benni_mac_b

Reputation: 8877

Float them both the same way and add the margin of 40px. If you have 2 elements floating opposite ways you will have much less control and the containing element will determine how far apart they are.

#left{
    float: left;
    margin-right: 40px;
}
#right{
   float: left;
}

Upvotes: 32

Related Questions