集中对齐ul元素

时间:2013-04-01 15:13:41

标签: html css

我正在尝试将一个ul元素与其上方的标题对齐。 ul元素包括联系信息列表(电子邮件,Twitter,RSS等)。这就是我到目前为止所做的:

unaligned

使用以下代码

实现

HTML

<html>
<head>
    <meta charset="utf-8" />
    <title>Jing Xue - Portfolio</title>
    <link rel="stylesheet" href="css/normalize.css" />
    <link rel="stylesheet" href="css/style.css" />
    <link href='http://fonts.googleapis.com/css?family=Delius+Swash+Caps' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Playfair+Display+SC:700' rel='stylesheet' type='text/css'>
</head>
<body>

<div class="header">
    <div class="wrapper">
    <h1>Portfolio of...</h1>    
    <h2>Jing Xue</h2>
    <ul class="intouch">
        <li class="twitter"><a href="">Twitter</a></li>
        <li class="rss"><a href="">RSS</a></li>
        <li class="email"><a href="">Email</a></li>
    </ul>
    </div>
</div>
</body>

CSS

body {
    background-color: rgb(255,255,255);
    color: rgb(59,67,68);
    margin: 0;
    padding: 0;
    font: 1em "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Verdana, Tahoma, sans-serif;
}

h1, h2, h3 {
    text-shadow: 1px 1px 2px rgba(0,0,0,0.3);
}

.wrapper {
    width: 940px;
    margin: 0 auto 0 auto;
}

/* header ------------------------------------------------------------------ */

.header {
    text-align: center;
    padding: 40px 0 0 0;
    margin-bottom: 40px;
}

.header h1, .header h2 {
     margin: 0;
}

.header h1 {
    font-family: 'Delius Swash Caps', cursive;
    font-size: 250%;
    color: rgb(200,50,50);
}

.header h2 {
    font-family: 'Playfair Display SC', serif;
    font-size: 450%;
    color: rgb(59,67,68);
}


.intouch {
    list-style: none;
    margin: 0 auto;
    padding: 0;
    width: 0;
}

.intouch li a:link, .intouch li a:visited {
  padding: 0.5em 0 0.5em 40px;
  display: block;
  font-weight: bold;
  background-repeat: no-repeat;
  background-image: url(../img/sprite-roll.png);
  text-decoration: none;
  color: rgb(136,136,136);
}

.intouch li.twitter a:link, .intouch li.twitter a:visited {
  background-position: 0 6px;
}

.intouch li.twitter a:hover {
  background-position: 0 -90px;
  color: rgb(105,210,231);
}

.intouch li.rss a:link, .intouch li.rss a:visited {
  background-position: 0 -30px;
}

.intouch li.email a:link, .intouch li.email a:visited {
  background-position: 0 -60px;
}

.intouch li.twitter a:hover {
  background-position: 0 -90px;
  color: rgb(105,210,231);
}

.intouch li.rss a:hover {
  background-position: 0 -126px;
  color: rgb(243,134,48);
}

.intouch li.email a:hover {
  background-position: 0 -156px;
  color: rgb(56,55,54);
}

正如您所看到的,.intouch ul类与其上方的标题不是中心对齐的。

我可以通过将margin-left: 425px;添加到.intouch类来实现居中对齐。产生这个:

aligned

我想知道的是,有没有更好的方法来实现这个中心对齐,而不是只添加左边距(我必须根据文字的长度改变?)

1 个答案:

答案 0 :(得分:2)

来自@Sparky的评论评论“如果没有宽度,你就无法自动居中。”我为.intouch添加了一个宽度:

.intouch {
   list-style: none;
   margin: 0 auto;
   padding: 0;
  width: 110px;
}

这完全集中了.intouch。随着.intouch的内容更改,width属性将被重新调整,保持元素居中。