要在不使用表的情况下创建宽度和高度相等的4列响应行?

时间:2018-04-17 17:21:39

标签: html css html5 css3

我正在尝试创建一个4列响应行,每列具有相同的宽度和高度,这些响应也是如此。我能够处理宽度,但无法处理高度。此外,列内的图像应该是响应的。 我在下面附上了我的代码:

<div class="container">
  <div class="header">
    <h1>Hello There</h1>
  </div>
  <!-- Given width:400px and height: 50px-->
  <div class="search">
    <input class="search-box" />
  </div>
  <div class="grid">
    <div class="grid-elements">
      <img       src="http://upload.wikimedia.org/wikipedia/commons/thumb/0/0d/Ski_trail_rating_symbol-blue_square.svg/600px-Ski_trail_rating_symbol-blue_square.svg.png">
    </div>
    <div class="grid-elements">
      <img src="https://vignette.wikia.nocookie.net/dragonballfanon/images/7/70/Random.png/revision/latest?cb=20161221030547">
    </div>
    <div class="grid-elements">
      <img src="http://kb4images.com/images/random-image/37670495-random-image.jpg">
    </div>
    <div class="grid-elements">
      <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSTS1hevM-88hmiqyYOeeCeVUTzCS63jl31LEyLAIjY7AKWXDVe">
    </div>
  </div>
</div>

这是css代码:

.header
{
  text-align:center;
}

.search
{
  margin: 25px 1.5%;
}

.search input
{
  display:block;
  margin:0 auto;
  width: 100%;
  height:50px;
  border:2px solid #f26522;
  border-radius:5px;
}

.grid
{
  display:flex;
}

.grid-elements
{
  width:25%;
  height:25%;
  margin:1.5%;
  border:1px solid #000;
  border-radius:3px;
}

.grid-elements img
{

 max-width: 100%;
 max-height:100%;
}

2 个答案:

答案 0 :(得分:1)

这里尝试使用CSS Grid

.grid {
  display: grid;
  grid-gap: 20px;
  grid-template-columns: 1fr 1fr 1fr 1fr;
}

.grid-elements {
  align-self: center;
}

.grid-elements img {
  width: 100%;
  height: auto;
}

https://jsfiddle.net/ksqmy5r6/6/

答案 1 :(得分:0)

替换:

.grid-elements
{
  width:25%;
  height:25%;
  margin:1.5%;
  border:1px solid #000;
  border-radius:3px;
}

使用:

.grid-elements
{
  flex: 1;
  margin:1.5%;
  border:1px solid #000;
  border-radius:3px;
}

flex: 1会使所有元素在父flex容器中占用相同的空间。

<强> Working Codepen