Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!


like image 334
Alex G Avatar asked Jan 23 '13 02:01

Alex G


People also ask

How do you float elements side by side?

Use CSS property to set the height and width of div and use display property to place div in side-by-side format. float:left; This property is used for those elements(div) that will float on left side. float:right; This property is used for those elements(div) that will float on right side.

How do you get rid of a float on the left?

To clear a float, add the clear property to the element that needs to clear the float. This is usually the element after the floated element. The clear property can take the values of left , right , and both . Usually you'll want to use both.


1 Answers

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.

like image 91
Mr Lister Avatar answered Sep 28 '22 06:09

Mr Lister