How to make a float to the left and swim right in one line?

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 look like this: enter image description here

, but my: enter image description here

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> 

CSS:

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


My solutions:

Solution 1 Use bootsrap to create a layout instead of doing it yourself, I use it on the footer and it works fine on one line! But I still don't know how it works enter image description here

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

Anyone can help? Many thanks!


+7
source share
5 answers

The reason it doesn't work is expected to be because the <ul> on the left expands to the right, thereby pushing the contents down. The solution could be to set an explicit fixed width for the left and right areas, which was done when I came across this scenario in the past. But they will say that a combination of floats and even absolute positioning is what ultimately will work.

+6
source

An alternative to the solutions already mentioned is to flip the markup order around, so there must first be a floating-point element.

 #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 do not have to do anything. No other CSS or markup is required.

+9
source

You must use absolute positioning and use left and right alignment.

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

Check out http://jsfiddle.net/A8SyJ

+2
source

Have you tried adding search as another list item in your navigator and floating right?

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

See an example below:

http://jsfiddle.net/teWP5/

0
source

You can use float: left for ul and float: on the right with a search field

0
source

All Articles