Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I center an element relative to its parent?

Tags:

css

I have the following container:

#container {
  width: 75%;
  margin: 0 auto;
  background-color: #FFF;
  padding: 20px 40px;
  border: solid 1px black;
  margin-top: 20px;
}

It was generated using nifty:layout Rails generator. How would I center something inside of this container, and not the entire page?

EDIT: Sorry for not providing further info :). This is what I'm trying to center:

<div id="nav">
    <ul>
        <% if current_user %>
            <li><%= link_to "Sign out",destroy_user_session_path %><span>|</span></li>
            <li><%= link_to "New snippet",new_snippet_path %><span>|</span></li>
        <% else %>
            <li><%= link_to "Login",new_user_session_path %><span>|</span></li>
            <li><%= link_to "Register",new_user_registration_path %><span>|</span></li>
        <% end %>
        <li><%= link_to "Snippets",snippets_path %><span>|</span></li>
        <li><%= link_to "Chat",messages_path %></li>
    </ul>
</div>

Here's the CSS I have for it so far:

#nav {
    list-style-type:none;
    padding:0;
    margin:0;
}

#nav li {
    display:inline;
}
like image 779
Geo Avatar asked Jun 11 '11 21:06

Geo


2 Answers

If you're trying to center the display: inline list elements, giving the container

text-align: center

will work.

If it's about block elements, @slhck's and @anirudh's answers are the solution.

like image 191
Pekka Avatar answered Nov 03 '22 04:11

Pekka


I guess the following should do. Assign a fixed width, and then

#inside-container {
  margin-left: auto;
  margin-right: auto;
  width: 50px;
}

You can specify top and bottom margins, but the auto value for left and right will make the element centered.

Update: Didn't see your code before. See @Pekka's answer for inline elements.

like image 28
slhck Avatar answered Nov 03 '22 04:11

slhck