Div Raj
Div Raj

Reputation: 31

Keep Text Centered when resizing

So I have looked at other questions like this, yet none have solved my problem. What I want to be able to do is resize the window of the browser, yet keep the text in the centre of the window.

HTML:

<div id=inside>
Navjeeven Mann
</div>

CSS:

#inside {
  position:relative;
  width: 100%;
  height: 100%;
  font-size: 60px;
  text-align: center;
  color: black;
  top:50%;
  left:50%;
}

What it looks like now

Upvotes: 0

Views: 5811

Answers (2)

cup_of
cup_of

Reputation: 6687

Looks like you want the text vertically and horizontally centered inside a div. I would first wrap your text inside a p tag. Then changeup the css a bit so your code will look like this:

    html, body {
      margin: 0;
    }
    
    #inside {
      position: relative;
      width: 100%;
      height: 300px; /* change this to your liking */
      border: 1px solid #000; /* to show size of div */
    }

    #inside p {
      position: absolute;
      left: 0;
      right: 0;
      top: 50%;
      transform: translateY(-50%);
      margin: auto;
      font-size: 60px;
      text-align: center;
      color: black;
      display: inline-block;
    }
    <div id="inside">
        <p>Navjeeven Mann</p>
    </div>

This should work across all devices

Upvotes: 0

Jonathan
Jonathan

Reputation: 6537

To keep it centred horizontally, remove the top:50%;left:50%;

#inside {
  position:relative;
  width: 100%;
  height: 100%;
  font-size: 60px;
  text-align: center;
  color: black;
}
<div id="inside">
  Navjeeven Mann
</div>

To center it horizontally and vertically, flex really does the job well, unless you have to support older browsers.

html, body {
  margin: 0;
}

#inside {
  display: flex;
  width: 100vw;
  height: 100vh;
  align-items: center;
  justify-content: center;
  font-size: 60px;
}
<div id="inside">
  Navjeeven Mann
</div>

Upvotes: 5

Related Questions