1028
1028

Reputation: 129

Center an h2 with respect to parent container

I would like to center an h2 with respect to its parent container (the rounded rectangle) but would also like the image (purple square) to vertically fill in the div as pictured below. The problem is that the height of the image overlaps with the h2 block element's box. Here is what I have so far using flexbox: enter image description here

.topic-ex {
  display: flex;
  flex-direction: column;
}

.topic-ex h2 {
  text-align: center;
}

.topic-ex-info {
  display: flex;
}
<div class="topic-ex">
  <h2>Text</h2>
  <div class="topic-ex-info">
    <img src="https://placeholder.pics/svg/500" alt="">
    <p>
      Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
    </p>
  </div>
</div>

Upvotes: 0

Views: 727

Answers (2)

Austin_K
Austin_K

Reputation: 58

Overflow: none; on purple box. You could also add a z-index of the purple box to something like +100 so it is in front of the border box but also will not overflow into the rest of the document because it is inside of the border box div and has a property of display with an attribute of none.

Upvotes: 0

marzique
marzique

Reputation: 694

I changed your html layout a little bit and also added a few new css rules: Fiddle

For h2 centering: I set parent container position: relative; and h2 position: absolute;.

left: 50%; shifts it to exact center by x axis, and transform: translate(-50%); shifts it back half of it's width.

HTML:

<div class="topic-ex">
   <h2>Text</h2>
  <img src="https://placeholder.pics/svg/500" alt="">
  <div class="topic-ex-info">
    <p>
      Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
    </p>
  </div>
</div>

CSS:

.topic-ex {
  display: flex;
  border: 3px solid black;
  border-radius: 30px;
  padding: 10px;
  justify-content: space-between;
  flex-wrap: nowrap;
  align-items: center;
  position: relative;
}

.topic-ex h2 {
  margin: 0;
  position: absolute;
  left: 50%;
  transform: translate(-50%);
  top: 0;
}

.topic-ex img{
  width: 150px;
  height: 150px;
}

.topic-ex-info {
  width: 70%;
}

enter image description here

just play with values to achieve exact same look if you need.

Upvotes: 1

Related Questions