Reputation: 57
I want #first
to be aligned to the left of #container
and #second
to the right.
For this, I'm using float: left;
on #first
and float: right;
on #second
.
This, however, results in #first
aligning left of the #container
and #second
just next to it. Why is this the case, and how can I achieve what I desire?
This is what I want:
This is what I'm getting:
Here's my code:
<head>
<style>
#container {
width: 500px;
margin: 0 auto;
border: 1px solid #000;
}
#first {
float: left;
}
#second {
float: right:
}
</style>
</head>
<body>
<div id="container">
<div id="first">
<p>first</p>
</div>
<div id="second">
<p>second</p>
</div>
</div>
</body>
Upvotes: 3
Views: 4296
Reputation: 3178
Well, well. No need to create an :after
-property for containing the floats, just use overflow: hidden;
on the container.
<head>
<style>
#container {
width: 500px;
margin: 0 auto;
border: 1px solid #000;
overflow: hidden;
}
#first {
float: left;
}
#second {
float: right;
}
</style>
</head>
<body>
<div id="container">
<div id="first">
<p>first</p>
</div>
<div id="second">
<p>second</p>
</div>
</div>
</body>
Upvotes: 5
Reputation: 3075
There are two things wrong. First of all you have a colon instead of semicolon near:
#second {
float: right: // <- change ':' to ';'
}
After you fix that you have to clear the content since both divs (#first and #second) are floated which causes container to have 0 height. You can achieve that using the following style:
#container:after {
display: table;
clear: both;
content: "";
}
See demo:
#container {
width: 500px;
margin: 0 auto;
border: 1px solid #000;
}
#container:after {
display: table;
clear: both;
content: "";
}
#first {
float: left;
}
#second {
float: right;
}
<div id="container">
<div id="first">
<p>first</p>
</div>
<div id="second">
<p>second</p>
</div>
</div>
Upvotes: 1
Reputation: 1114
Surprisingly enough, this also sometimes does the trick.
#container {
width: 500px;
margin: 0 auto;
border: 1px solid #000;
}
#first {
float: right;
}
#second {
float: right:
}
<body>
<div id="container">
<div id="first">
<p>goes right</p>
</div>
<div id="second">
<p>goes left</p>
</div>
</div>
</body>
Upvotes: 0
Reputation: 41
Assuming that #container is positioned relatively, we could do this to get the result you want:
#container {
width: 500px;
margin: 0 auto;
border: 1px solid #000;
}
#first {
position:absolute;
left:0;
height:100%;
}
#second {
position:absolute;
right:0;
height:100%;
}
Your current css is not working because float:right and float:left simply determine how the DOM elements interact with their siblings; Not their parents. If you wants the children divs of #first and #second to not fill the parent div you can also change height property on them to whatever you want.
Upvotes: 0