How can I center an element relative to this parent?

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 concentrate something inside this container, and not the entire page?

EDIT: Sorry for the lack of additional information :). This is what I'm trying to focus on:

 <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 is the CSS that I still have:

 #nav { list-style-type:none; padding:0; margin:0; } #nav li { display:inline; } 
+6
source share
3 answers

If you try to center the display: inline list items by providing a container

 text-align: center 

will work.

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

+5
source

I think the following should be done. Assign a fixed width and then

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

You can specify the upper and lower margins, but the auto value for the left and right elements will make the element in the center.

Update: I have not seen your code before. See @Pekka's answer for inline elements.

+2
source

Make a div with id="container" , have a class class="container" and do

 .container #innerElement { position: relative; width: <set width here>; margin: auto; } 
+1
source

Source: https://habr.com/ru/post/890305/


All Articles