0

I have an inner (child) div inside an outer (parent) div.

Inner div is both horizontally as well as vertically center aligned inside the outer div. Used table-cell & vertical-align: middle on parent element and display: inline-block in child element.

I want to center align the text inside the inner div both horizontally as well as vertically.

This question may seem to be duplicate, but it is not. The solutions provided on other links are usually based on -

  1. line-height: which I feel is not a good solution because it depends on the parent's height.
  2. display: table-cell: Inner element is already an inline-block in my solution, can't keep another display property on the same block.
  3. Flex: is something which I am not aware of, hence accepted the solution posted by @xenio-gracias.

How to achieve this?

Here's my current working code:

/* Lesson 3 (PART 1): div inside div */
.outer-lesson3 {
 border: 1px solid lightcoral;
 display: table-cell;
 width: 300px;
 height: 300px;
 vertical-align: middle;
 text-align: center;
}

.inner-lesson3 {
 border: 1px solid mediumseagreen;
 display: inline-block;
 width: 100px;
 height: 150px; 
}
/* Lesson 3 (PART 1) ENDS */
<html>

<head>
    <link rel="stylesheet" href="prac.css">
</head>

<body>
    <!-- Lesson 3 -->
    <div class="outer-lesson3">
        <div class="inner-lesson3">
            Horizontally & Vertically Center 'div' inside 'div'
        </div>
    </div>
</body>

</html>
Pranjal Successena
  • 907
  • 1
  • 11
  • 24
  • @paulie-d, this is not duplicate. The solutions given at the mentioned linked are not going to work for my scenario. Even if I want them to work, I will have to change my solution which is entirely a different scenario. – Pranjal Successena Mar 12 '19 at 12:46

1 Answers1

2

used flexbox to achieve it Hope this helps. thanks

/* Lesson 3 (PART 1): div inside div */

.outer-lesson3 {
  border: 1px solid lightcoral;
  display: table-cell;
  width: 300px;
  height: 300px;
  vertical-align: middle;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

.inner-lesson3 {
  border: 1px solid mediumseagreen;
  display: inline-block;
  width: 100px;
  height: 150px;
  display: flex;
  align-items: center;
  justify-content: center;
}


/* Lesson 3 (PART 1) ENDS */
<html>

<head>
  <link rel="stylesheet" href="prac.css">
</head>

<body>
  <!-- Lesson 3 -->
  <div class="outer-lesson3">
    <div class="inner-lesson3">
      Horizontally & Vertically Center 'div' inside 'div'
    </div>
  </div>
</body>

</html>
Xenio Gracias
  • 2,728
  • 1
  • 9
  • 16