如何将元素相对于其父元素居中? [英] How can I center an element relative to its parent?

查看:30
本文介绍了如何将元素相对于其父元素居中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下容器:

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

它是使用nifty:layout Rails生成器生成的.我如何在容器中而不是整个页面中放置某些内容?

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

很抱歉没有提供更多信息:).这就是我要尝试的重点:

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>

这是到目前为止我拥有的CSS:

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

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

#nav li {
    display:inline;
}

推荐答案

如果您试图将 display:inline 列表元素居中放置,请给容器

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

text-align: center

将起作用.

如果是关于块元素,则@slhck和@anirudh的答案就是解决方案.

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

这篇关于如何将元素相对于其父元素居中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆