Samuel
Samuel

Reputation: 462

How to change the style of parent div that has a rotated image with CSS in Angular 5 project?

I was building a meme with top and bottom text. I am in need of rotating an image so I did it with transform: rotate(90deg);, but it's overlapped parent's div like the following example.

h1 {
  margin-top: 100px;
}

.parent {
  border: 1px solid black;
  display: inline-block;
  position: relative;
  background: #777;
}

.parent .rotate {
  transform: rotate(90deg);
  width: 100px;
}

.parent h4 {
  position: absolute;
  left: 0;
  right: 0;
  text-align: center;
  color: white;
  z-index: 1;
}

.parent .top {
  top: 10px;
}

.parent .bottom {
  bottom: 10px;
}
<div class="parent">
  <h4 class="top">Top Text</h4>
  <img class="rotate" src="http://2.bp.blogspot.com/-7uOyzdXhG2Y/UVpJUbwqGzI/AAAAAAAAAo0/35w5N8tPvHE/s640/iphone-5-hd-wallpapers-hd-41664-tpmw7.jpg" />
  <h4 class="bottom">Bottom Text</h4>
</div>

How can I change the style of the parent div to match the position and size of the rotated image?

Upvotes: 1

Views: 201

Answers (1)

Julian W.
Julian W.

Reputation: 1571

First, we need to change the height of the div to be same as width.

We can do it by

.parent{
  background-color: red;
  width: 100%;
  padding-top: 100%; /* 1:1 Aspect Ratio */
  position: relative; /* If you want text inside of it */
}

Second, we need an additional div inside it that has absolute position with full width and height of it.

We can use flex to center the image inside that absolute div.

Here is a working code.

h1 {
  margin-top: 100px;
}

.container {
  display: inline-block;
  width: 300px;
}

.parent {
  border: 1px solid black;
  display: inline-block;
  position: relative;
  background: #777;
  width: 100%;
  padding-top: 100%;
  position: relative;
}

.p-absolute {
  bottom: 0;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  margin-top: auto;
  margin-bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.parent .rotate {
  transform: rotate(90deg);
  max-width: 100%;
  max-height: 100%;
}

.parent h4 {
  position: absolute;
  left: 0;
  right: 0;
  text-align: center;
  color: white;
  z-index: 1;
}

.parent .top {
  top: 10px;
}

.parent .bottom {
  bottom: 10px;
}
<div class="container">
  <div class="parent">
    <h4 class="top">Top Text</h4>
    <div class="p-absolute">
      <img class="rotate" src="http://2.bp.blogspot.com/-7uOyzdXhG2Y/UVpJUbwqGzI/AAAAAAAAAo0/35w5N8tPvHE/s640/iphone-5-hd-wallpapers-hd-41664-tpmw7.jpg" />  
    </div>
    <h4 class="bottom">Bottom Text</h4>
  </div>
</div>

Upvotes: 1

Related Questions