1

I am trying to center a span inside a div element. I have the code below:

<!DOCTYPE html>
<html>
    <head>
        <style>
        .parent {
            border: 1px solid red;
            height: 100px;
            width: 200px;
             position: relative;
        }
        .child {
            border: 1px solid green;
            position: relative;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
        </style>
    </head>
    <body>
        <div class="parent">
            <span class="child">This is a span.</span>
        </div>
    </body>
</html>

The span is not really centred in the div. However, when I apply:

position: absolute;

on the .child css style, it works. What's the reason behind this?

injoy
  • 3,993
  • 10
  • 40
  • 69
  • 1
    A span is an inline element. Either make it a div or add inline-block. Marking an element as absolute removes it's width/"flow" from the DOM. – J Set Mar 19 '18 at 02:41

0 Answers0