如何用h1和h2正确确定ul,li和a的中心?

时间:2018-12-15 06:57:37

标签: html css

给出的将身体居中的原始建议会导致ul,li,而不是正确居中:

.jumbotron h1, .jumbotron h2 {
text-align: center;    
}

.jumbotron {
    position: relative;
    top: -9px
    padding: 75px 0px 75px 0px;
}

.jumbotron ul, .jumbotron li, .jumbotron a {
    display: inline;
    text-decoration: none;
}

我尝试的解决方案: 这个似乎效果最好,但是必须有一种方法可以使身体居中并使所有元素对齐。

.jumbotron {
  position: relative;
  text-align: center;
  top: -9px;
  /*Extend out div use padding */
  padding: 75px 0px 75px 0px;
}

.jumbotron ul,
.jumbotron li,
.jumbotron a {
  display: inline;
  padding: 75px 10px 75px 10px;
  text-decoration: none;
}
<div class="jumbotron">
  <h1>
    abcde
  </h1>
  <h2>
    abcde
  </h2>
  <ul>
    <li><a href="#contact">Contact</a></li>
    <li><a href="#resume">Resume</a></li>
  </ul>
</div>

3 个答案:

答案 0 :(得分:0)

尝试一下:

.jumbotron {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100%;
  width: 100%;
  >* {
    flex: 1;
  }
}
<div class="jumbotron"> 
 <h1> abcde </h1> 
 <h2> abcde </h2> 
 <ul>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#resume">Resume</a></li>
 </ul> 
</div>

答案 1 :(得分:0)

我只是将您的显示属性更改为“阻止”并将填充减少到了10px(例如)

.jumbotron {
  position: relative;
  text-align: center;
  top: -9px;
  /*Extend out div use padding */
  padding: 75px 0px 75px 0px;
}

.jumbotron ul,
.jumbotron li,
.jumbotron a {
  display: block;
  padding: 10px;
  text-decoration: none;
}
<div class="jumbotron">
  <h1>
    abcde
  </h1>
  <h2>
    abcde
  </h2>
  <ul>
    <li><a href="#contact">Contact</a></li>
    <li><a href="#resume">Resume</a></li>
  </ul>
</div>

答案 2 :(得分:0)

Flexbox可以为您提供很大的帮助(我为不同的解决方案评论了我的CSS):

/** simply way to reset some paddings & margins for this demo: use normalize.css to a better solution => https://necolas.github.io/normalize.css/ */

* {
  margin:0;
  padding:0;
}

/* those rules are used to center vertically your jumbotron div. Remove the comment if you need it. */

/*body{
  display:flex;
  height:100vh;
  align-items:center;
  justify-content:center;
}*/

.jumbotron {
  padding-top:75px; /* remove this line and the comment above to center vertically your jumbotron */
  display:flex;
  flex-direction:column;
  align-items: center;
}

ul {
  display:flex; /* remove this rule if you want to have all the elements one below the other*/
}

li {
  list-style: none;
  margin:10px;
}

a{
  text-decoration:none;
}
<body>
  <div class="jumbotron">
    <h1>abcde</h1>
    <h2>abcde</h2>
    <ul>
      <li><a href="#contact">Contact</a></li>
      <li><a href="#resume">Resume</a></li>
    </ul>
  </div>
</body>