如何在容器中垂直和水平居中div

时间:2017-07-14 05:35:42

标签: jquery html css css3

我有以下标记:

<div class="wrapper">
  <div class="block new-block"></div>
  <div class="block used-block"></div>
  <div class="block service-block"></div>
  <div class="block certified-block"></div>
  <div class="block offer-type-block"></div>
</div>

以下css:

.wrapper {
  width : 800px;
  height : 100px;
  background : #393533;
  margin : auto;
}

.block {
  width : 19%;
  height : 80px;
  background : salmon;
  display : inline-block;
}

我想在容器包装容器中水平和垂直居中5个div,我怎么能用css实现这个目的。谢谢你!

3 个答案:

答案 0 :(得分:2)

一种方法是在包装器上使用CSS flexbox并将内容对齐到中心:

.wrapper {
  width : 800px;
  height : 100px;
  background : #393533;
  margin : auto;
  display: flex;
  justify-content: center;
}

.block {
  width : 19%;
  height : 80px;
  background : salmon;
  display : inline-block;
  align-self: center;
}
<div class="wrapper">
  <div class="block new-block">test</div>
  <div class="block used-block">test</div>
  <div class="block service-block">test</div>
  <div class="block certified-block">test</div>
  <div class="block offer-type-block">test</div>
</div>

答案 1 :(得分:0)

请尝试以下代码。可能它可以帮助你

 .wrapper {
        width : 800px;
        height : 100px;
        background : #393533;
        margin : auto;
        position: relative;
      }

答案 2 :(得分:0)

&#13;
&#13;
<!DOCTYPE html>
<html>
<head>
	 <title> Sample Code </title>
	 <style>
.wrapper {
    width: 800px;
    height: 120px;
    background: #393533;
    margin: auto;
    padding: 20px;
    box-sizing: border-box;
    text-align: center;
}
.block {
  width : 19%;
  height : 80px;
  background : salmon;
  display : inline-block;
}
	 </style>
</head>
<body>

<div class="wrapper">
  <div class="block new-block"></div>
  <div class="block used-block"></div>
  <div class="block service-block"></div>
  <div class="block certified-block"></div>
  <div class="block offer-type-block"></div>
</div>



   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
   <script>

   </script>
</body>
</html>
&#13;
&#13;
&#13;