Alfred
Alfred

Reputation: 21386

Display two divs in a single line filling space - CSS

I have two divs diva and divb. They have a fixed height of 30px. I want to display them in a single line, one after the other. This can be done by giving them widths of 10% and 90% respectively and by float: left. This works fine. But I gave them a border of 1 px and this disturbs the calculation. I gave the second div a width of 88% and is working. But there is an empty space after that div.

I want both the divs to display in a single line. The page re sizes and I want divs to fill space and so that I can't give them fixed width. The first div may be given a fixed width, because I just want it 150 px wide. But the second div must be wider to fill space.

What I am getting is this;

Current layout

and I want this:

Expected layout

Here is the fiddle.

Upvotes: 3

Views: 42998

Answers (6)

arun
arun

Reputation: 1

<div style="display:table">
    <div style="display: inline-block;width:100px;height:100px;background-color:red;">DIV 1</div>
    <div style="display: inline-block;width:100px;height:100px;background-color:green;">DIV 2</div>
    <div style="display: inline-block;width:100px;height:100px;background-color:blue;">DIV 3</div>
</div>

Upvotes: 0

Ollie
Ollie

Reputation: 656

Try this

 body{
     margin: 0;
 }
 #div1{
     height: 30px;
     width: 10%;
     outline: solid 1px #000000;
     background-color: #0066CC;
     float: left;
 }
 #div2{
     height: 30px;
     width: 90%;
     outline: solid 1px #000000;
     background-color: #66CC00;
     float: left;
 }​

Not so great for IE though

Upvotes: 4

Henrik Andersson
Henrik Andersson

Reputation: 47172

Add a width: 100% to the body and specify float: left; on div1 and remove the float: left; on the div2.

If you're using percentage widths or heights on child elements you have to specify a percentage width or height on the parent or rather container element as well.

That should fix it! :)

See this fiddle here

Good luck!

Upvotes: 11

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123377

http://jsfiddle.net/J7mJX/1/

just add

#div1, #div2 {
    -webkit-box-sizing: border-box;  
    -moz-box-sizing: border-box;  
    box-sizing: border-box;   
}

so the border is included on width calculation.

Upvotes: 3

Ollie
Ollie

Reputation: 656

Alternatively you can add extra divs that wont affect the width of the parent div with the added border

http://jsfiddle.net/ollie/76Raj/9/

Upvotes: 0

Joe Flateau
Joe Flateau

Reputation: 1225

Set box-sizing:border-box; on the floated divs with % widths.

https://developer.mozilla.org/En/CSS/Box-sizing

Upvotes: 2

Related Questions