Reputation: 41
I have a div called menu, inside it I want to have a navigation bar div and a search div. I want that the navigation stays in center of the menu div and the search div goes to the left (or right). I tried this code but when I set the position to absolute, setting navigation's left and right margins to auto doesn't work.
CSS code:
.menu{
width: 100%;
height: 65px;
margin-bottom: 0.5%;
}
.search{
width: 300px;
height: 65px;
float:left;
z-index: 1;
position:absolute;
}
.navigation{
height: 65px;
margin-left: auto;
margin-right: auto;
z-index: 0;
display:inline-block;
position: absolute;
}
HTML code:
<div class="menu">
<div class="navigation">
.
.
.
</div>
<div class="search">
.
.
.
</div>
</div>
Upvotes: 2
Views: 2039
Reputation: 8220
If you want make a navigation to center of menu (stay on center). Try this :
.menu{
width: 100%;
height: 65px;
margin-bottom: 0.5%;
margin-top:5px;
}
.search{
width: 300px;
height: 65px;
float:left;
z-index: 1;
}
.navigation{
width:300px; /* you can change this */
left: 50%; /* you can change this */
margin-left: -150px; /* you can change this */
height: 65px;
display:inline-block;
position: absolute;
}
First, left: 50%
. this will move the left-hand edge of the navigation to the center.
use a negative left margin that’s half its width (width of navigation div : 300px
). In our example, must set margin-left
to -150px
to shift the box back to the right place
Update 2015
You can do it without 'position', you can use flexbox
.menu {
width: 100%;
height: 65px;
margin-top: 5px;
display: -webkit-flex;
display: flex;
-webkit-flex-wrap: wrap;
flex-wrap: wrap;
-webkit-justify-content: center;
justify-content: center;
}
.search{
width: 300px;
height: 65px;
margin-left:10px;
}
.navigation{
width:300px;
height: 65px;
margin:0 auto;
margin-left:220px;
}
.navigation ul {
list-style:none;
margin-top:5px;
}
.navigation ul li {
float:left;
margin-left:5px;
border:solid 1px;
}
Upvotes: 1
Reputation: 737
Since in your case you can specify widths, Its always better to use inline-blocks instead of floats. hope this helps
.menu{
width: 100%;
height: 65px;
margin-bottom: 0.5%;
letter-spacing: -0.31em;
}
.search{
width: 300px;
height: 65px;
float:left;
z-index: 1;
border:1px solid green;
letter-spacing: normal;
}
.navigation{
height: 65px;
margin-left: auto;
margin-right: auto;
z-index: 0;
display:inline-block;
letter-spacing: normal;
text-align:right;
border:1px solid blue;
}
Upvotes: 0
Reputation: 77
I think user2391454 has you on the right track. Position gets confusing sometimes, but leaving it out completely might help you. Take out all of your positions in your CSS and see if that works.
Let us know.
Upvotes: 0
Reputation: 640
position: absolute doesnt work with floating. you have to actually set the pixels from the left and from the top you want the absolute positioned element.
it sounds like you dont even really need absolute positioning,
http://codepen.io/anon/pen/KtgBa
Upvotes: 0