Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

html - Responsive squares divs

I want to have a column with 4 divs with a background-image and fit the 100% of the parent width and give the same to the height to make a square. This is what i have without %:

enter image description here

My HTML:

<div class="col-sm-3 slots" style="background-color: red;">
    <div class="slot"></div>
    <div class="slot"></div>
    <div class="slot"></div>
    <div class="slot"></div>
</div>

And my CSS with width and height in pixels.

.slot {
    background-image: url("img/Inventory_slot_background.png");
    background-repeat: no-repeat;
    width: 68px;
    height: 68px;
}
.slots {
    padding: 0;
}

I want to give width: 100%; and then something like height: width;

Edit: The problem is that if i use the padding-bottom: 100%; if i want to put text or images, the backgrund expands and look like this:

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You may use a pseudo element:

.slot {
  box-shadow:inset 0 0 5px #C9A170;
  background:#EBE6C9;
  border:solid #78624A;
  overflow:hidden;
  padding:5px;
  margin:1em;
  }
.slot:before {
  content:'';
  float:left;
  padding:50% 0;
  }
body {
  margin:0;
  }
<div class="col-sm-3 slots" style="background-color: red;">
    <div class="slot"> anything here</div>
    <div class="slot"> can grow taller than the initial square shape</div>
    <div class="slot"></div>
    <div class="slot"></div>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...