Alex G
Alex G

Reputation: 1610

How to make the float left and float right on the same line?

The Problem:

     **The left part** (#nav ul li) which float: left
     and **the right part** (#nav .search) which float: right
            **are not in a line**.

it should be like this: enter image description here

but mine: enter image description here

The HTML:

<div id="nav">
   <ul>
     <li><a href="#">Home</a></li>
     <li><a href="#">Portfolio</a></li>
     <li><a href="#">Blog</a></li>
     <li><a href="#">Contact</a></li>
   </ul>
   <div class="search">
     <input type="text" name="search" id="search" value="search">
   </div>       

The CSS:

#nav ul li{
float: left;
list-style: none;
margin: 0 20px;
}

#nav .search{
float: right;
}


My Solutions:

Solution 1: Use bootsrap to build layout instead of doing it on my own, i use it on the footer, and it's perfectly on the same line! Yet I still don't know how it works enter image description here

Solution 2: I use margin-top: -20px to pull the search box up, but I don't think it is a good practice.

Any one can help? Many thanks!


Upvotes: 14

Views: 39799

Answers (5)

Giacomo1968
Giacomo1968

Reputation: 26024

The reason it doesn’t work as expected is that the <ul> on the left is expanding out to the right, thus pushing the content down. The solution might be to set an explicit fixed width for the left and right areas which is what I have done when I have faced this scenario in the past. But will say that a mix of floats and even absolute positioning is what will ultimately work.

Upvotes: 9

Mr Lister
Mr Lister

Reputation: 46629

An alternative to the solutions already mentioned is to flip the order of the markup around, so that the right-floating item comes first.

#nav ul li {
  float: left;
  list-style: none;
  margin: 0 20px;
}
#nav .search {
  float: right;
}
<div id="nav">
   <div class="search">
     <input type="text" name="search" id="search" value="search">
   </div>       
   <ul>
     <li><a href="#">Home</a></li>
     <li><a href="#">Portfolio</a></li>
     <li><a href="#">Blog</a></li>
     <li><a href="#">Contact</a></li>
   </ul>
</div>

You don't have to do anything else. No other CSS or markup is needed.

Upvotes: 16

nexus_07
nexus_07

Reputation: 143

You can use float:left for the ul and float: right with the search box

Upvotes: 0

Jon P
Jon P

Reputation: 821

You have to use absolute positioning and use left and right alignment.

#nav ul, #nav .search {
    margin: 5px;
    position: absolute;
    display: inline-block;
}

Check here http://jsfiddle.net/A8SyJ

Upvotes: 4

jjsquared
jjsquared

Reputation: 299

Have you tried adding the search as another list item within your nav and floating that to the right?

<li class="search"><input type="text" name="search" id="search" value="search"></li>

See the example below:

http://jsfiddle.net/teWP5/

Upvotes: 0

Related Questions