1

I've this code :

.container {
  width: 100%;
  margin: 30px;
}
.container div {
  width: 100px;
  height: 100px;
  transform: rotate(-45deg);
  background: blue;
  display: inline-block;
}
<div class="container">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

I want these divs to fit whatever the .container width is. I want to set dynamic width and height to them.

Thanks for your help !

user229044
  • 232,980
  • 40
  • 330
  • 338
Corentin Branquet
  • 1,556
  • 3
  • 17
  • 29

2 Answers2

2

CSS handles the rotation after painting the element, so we can't just use width: 25% for the diamonds, we will have to be smarter.

Using some geometry:

  • The formula for the width would be 25% / sqrt(2) (which is approx. 17.677%)

  • The formula for the margins would be (25% - (25% / sqrt(2))) / 2 (which is approx. 3.661%)

Don't use display: inline-block here because it adds a tiny gap of about 4px between elements; use float: left instead.

Here are your diamonds! (Using this method for styling the divs as squares)

.container {
  width: 100%;
  height: 180px;
  background: gray;
}
.container div {
  width: 17.677%;
  padding-bottom: 17.677%;
  margin: 3.661%;
  transform: rotate(45deg);
  background: blue;
  float: left;
}
<div class="container">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

I've added a background color so that you can see the size of the container. If you also want the height of the container to fit the diamonds, I made a JSFiddle that makes a small modification.

Community
  • 1
  • 1
4castle
  • 32,613
  • 11
  • 69
  • 106
0

You should use some percentages here if you want an easy method. Also replace inline-block with a float. Worth noting if you use a float, make sure you clear the parent container to avoid and layout issues...

css:

.container {
  width: 100%;
}
.container div {
  width: 25%;
  transform: rotate(-45deg);
  background: blue;
  float: left;
}
.container div:before {
  content: "";
  padding-top: 100%;
  display: block;
}

See Example

Gerico
  • 5,079
  • 14
  • 44
  • 85
  • It's working, I want them to be next to each other by the peak, because here they are over each other – Corentin Branquet Apr 21 '16 at 13:18
  • @Doidgey, please use clear:both whenever you are using float as then you are not able to check them in inspect and you will get white space issue. updated your fiddle. Check https://jsfiddle.net/LeoLion/eLv3uwth/4/ – Leo the lion Apr 21 '16 at 13:19