如何居中div元素?

时间:2020-05-28 04:27:50

标签: html css

我正在尝试在页面上将div元素居中,但是似乎没有任何效果。当前div网格结构“图库”被推到左侧的like this处,但是我想将其居中-它的子元素的flex属性与它有什么关系,如何最好地使其居中? >

.album {
  margin: 0;
  overflow: hidden;
}

.image {
  display: inline-block;
  margin-bottom: 8px;
  margin-right: 8px;
  text-decoration: none;
  color: black;
  cursor: pointer;
}

.image:nth-of-type(2n) {
  margin-right: 0;
}

.image:hover img {
  transform: scale(1.15);
}

img {
  border: none;
  max-width: 100%;
  height: auto;
  display: block;
  background: #ccc;
  transition: transform .2s ease-in-out;
}

.gallery {
  margin-top: 1em;
  background-color: #86b3d1;
  display: flex;
  flex-wrap: wrap;
}

.main {
  background-color: #86b3d1;
}
<div class="main">
  <div class="title">
    <div class="inner-width">
      <div class="viewing">Viewing the Collection for</div>
      <div class="name">{{ place_name }}</div>
      <div class="address">at {{ address }}</div>
    </div>
  </div>
  <div class="gallery">
    {% for song, posts in posts_dict.items() %}
    <div class="album">
      <audio id="{{ song.song_uri[14:] }}" src="{{ song.song_preview }}"></audio>
      <img src="{{ song.album_picture }}" class="image" alt="" onmouseover="start('{{ song.song_uri[14:] }}')" onmouseout="stop('{{ song.song_uri[14:] }}')" onclick="playorpause('{{ song.song_uri[14:] }}')">
    </div>
    {% endfor %}
    <div class="album">
      <a href="{{ url_for('search_music', place_id=place_id, address=address) }}"><button class="add-button" >Add a song</button></a>
    </div>
  </div>
</div>

3 个答案:

答案 0 :(得分:0)

.gallery {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
有关更多说明,请参考-> https://www.freecodecamp.org/news/how-to-center-things-with-style-in-css-dc87b7542689/

答案 1 :(得分:-1)

body{
display: flex;
align-items: center; 
margin: 0 auto;
width: 100%;
}

.gallery{
 width: 80%;
}

答案 2 :(得分:-1)

只需添加以下CSS:-

justify-content: center;

转到您的.gallery类以使其居中对齐。这就是你想要的吗?