What is the best way to center text vertically within a div in HTML?

Is there a way to center text along the vertical axis of a div in HTML? I've already tried using text-align:center;, but that only works for the horizontal axis. Is there an equivalent method for the Y axis? I want to apply this to all divs with the class .subcol and the div with the id #top.

body {
  margin: 15px;
}

.subcol {
  background: teal;
  color: white;
  border-radius: 7px;
  text-align: center;
  margin: 0 5px 5px 0;
  height: 50px;
}

#top {
  background: cyan;
  width: 100%;
  height: 150px;
  text-align: center;
  font-style: bold;
}
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

<div id="top">Hello World Page</div>
<div class="row">
  <div class="col-lg-6 col-sm-12">
    <div class="subcol">
      Hello World 1
    </div>
  </div>
  <div class="col-lg-6 col-sm-12">
    <div class="subcol">
      Hello World 2
    </div>
  </div>
  <div class="col-lg-6 col-sm-12">
    <div class="subcol">
      Hello World 3
    </div>
  </div>
  <div class="col-lg-6 col-sm-12">
    <div class="subcol">
      Hello World 4
    </div>
  </div>
</div>

Answer №1

You can easily center elements using flexbox:

display: flex;
justify-content: center;
align-items: center;

justify-content: center -> to center horizontally.

align-items: center -> to center vertically.

Simply apply this CSS to the classes you want to center.

Here is an example of how it works in action:

        body{
            margin:15px;
        }
        .subcol {
            background:teal;
            color:white;
            border-radius:7px;
            text-align:center;
            margin:0 5px 5px 0;
            height:50px;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        #top {
            background:cyan;
            width:100%;
            height:150px;
            text-align:center;
            font-style:bold;
                        display: flex;
            justify-content: center;
            align-items: center;
        }
    <div id="top">Hello World Page</div>
    <div class="row">
        <div class="col-lg-6 col-sm-12">
            <div class="subcol">
                Hello World 1
            </div>
        </div>
        <div class="col-lg-6 col-sm-12">
            <div class="subcol">
                Hello World 2
            </div>
        </div>
        <div class="col-lg-6 col-sm-12">
            <div class="subcol">
                Hello World 3
            </div>
        </div>
        <div class="col-lg-6 col-sm-12">
            <div class="subcol">
                Hello World 4
            </div>
        </div>
    </div>

Answer №2

Set the line-height to match the height of your div.

 body{
            margin:15px;
        }
        .subcol {
            background:teal;
            color:white;
            border-radius:7px;
            text-align:center;
            margin:0 5px 5px 0;
            height:50px;
            line-height:50px; /* added */
        }
        #top {
            background:cyan;
            width:100%;
            height:150px;
            line-height:150px;  /* added */
            text-align:center;
            font-style:bold;
        }
    <title>Bootstrap Test</title>
    <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

    <div id="top">Hello World Page</div>
    <div class="row">
        <div class="col-lg-6 col-sm-12">
            <div class="subcol">
                Hello World 1
            </div>
        </div>
        <div class="col-lg-6 col-sm-12">
            <div class="subcol">
                Hello World 2
            </div>
        </div>
        <div class="col-lg-6 col-sm-12">
            <div class="subcol">
                Hello World 3
            </div>
        </div>
        <div class="col-lg-6 col-sm-12">
            <div class="subcol">
                Hello World 4
            </div>
        </div>
    </div>

Answer №3

There are countless techniques in HTML & CSS

The method I prefer to use is the following.

I trust that this information has been beneficial to you

.box {
  width: 100px;
  height: 20px;
  position: relative;
  border: 1px solid red;
}

.inner-box {
  width: 10px;
  height: 5px;
  border: 1px solid blue;
}

centered {
  position: absolute;
  top: 50%;
  left: 50%;
  transform:translate(-50%, -50%)
}
<div class='box'>
  <div class='inner-box centered'></div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enhancing Drupal Views: Changing Filter Criteria from Dropdown to Autocomplete

After setting a new filter criteria in a view, I am trying to make it show as a drop-down instead of autocomplete. I have clicked on settings (next to the name of the new criteria), selected Drop down, and clicked Apply (all displays). However, on preview ...

Guide on aligning text below an image at the same height through flexbox styling

I am trying to use flexbox to make two images side by side have the same height and align the text under the image. Can anyone assist me with this issue? Here is the code I am currently using: .row{ display:flex; } .cell img{ width:150px ...

Using TempData in conjunction with Bootstrap is not permitted

While working on my web application, I came across a Bootstrap implementation done exceptionally well by someone else. Excited to use it, I incorporated the code but ran into a compile error CS1061 in the NotificationExtensions.cs file. Success message f ...

How can you locate the position of identified text on a webpage to accurately place the mouse cursor there?

When browsing a webpage in my web browser (preferably Firefox), I have the ability to search for a specific text "abc" using ctrl+f. Once found, I need to move my mouse cursor to another relative position on the page and click. Unfortunately, the necessar ...

What is the best method to retrieve child elements from a class list object?

Seems like I have a similar content class <div class="parentclass"> <div class="childClass"> </div> <div class="childClass"> </div> <div class="childClass"> </d ...

The table row disappears but the value persists

I have designed a table where users can perform calculations. However, when a row is deleted, the values from that row appear in the row below it and subsequent rows as well. What I want is for the user to be able to completely remove a row with its values ...

Using the curl command, incorporate JSON data into an already established array

I've been working with PHP to use curl and send an HTML post request. My goal is to include additional data to an existing JSON array located at a particular URL. When I send the request, I'm unsure if the data will be replaced or added to the ex ...

Iterate over div elements using jQuery

I am experimenting with creating a jQuery slider using divs: <div id="block-1"> <div id="bannerleft"> <div class="wsite-header-1"></div> </div> <div id="bannerright"> < ...

Issue: Inadequate Scope Permissions

Currently, I am working on a web application designed to post on the stocktwits wall. However, I have encountered an issue stating "Insufficient Scope Permissions." Does anyone have insight into where this error may be coming from? Here is a snippet of my ...

Accordion styling using CSS

My current issue lies with setting the style for the contents of an accordion. The problem arises when the styles defined in a CSS file do not take effect on the content of my accordion when using the following code along with a separate CSS file: <scr ...

Issues with PHP Mail Forms not functioning as intended

I've been struggling for hours trying to figure this out. I'm new to PHP mail form coding and any assistance would be greatly appreciated! Below are two images: one of the HTML code and one of the PHP code. It seems like a simple setup, but even ...

Tips on implementing taxonomy-driven CSS styling with Drupal's template.php file?

Currently, I am excited about incorporating CSS styling based on taxonomy terms, particularly for the body tag where I aim to include the current terms. Here is my progress so far : function _phptemplate_variables($hook, $vars = array()) { global $no ...

Error: Collision detection in Three.js console output

I am attempting to create a collision detection system using Three.js (a WEBGL library). However, I keep encountering an error stating "cannot call method multiplyVector3 of undefined". Is there anyone who can help me identify what I may be doing incorrec ...

Steps for displaying the search results in a pop-up box

I'm having trouble figuring out what to put in the '()' of my JavaScript popup function. Can anyone help me with this issue? Thank you! :) <script> // Example of JavaScript popup window function function customPopup(url) { popupWindow ...

Altering the flex-direction causes my divs to vanish into thin air

Just starting out with css, trying to get some practice. I'm attempting to position two divs on opposite sides of a parent div. Switching flex-direction from 'column' to 'row' causes the divs to disappear. #assignments-wrapp ...

Creating dynamic menu elements in HTML

How can I create movable menu items in HTML? Currently, I have four menu items arranged vertically in the right corner of my site like: Home Services Contact About I would like to make it so that when the user clicks on a menu item, it moves to the top ...

The deletion feature on my virtual keyboard was malfunctioning when using JavaScript

The virtual keyboard feature I added to my website isn't working properly, specifically the delete function. How can I fix this issue? Below is my code: HTML Code <input type="text" maxlength="12" min="10" name="msidn" id="jkeyboard" min="1" sty ...

Utilizing Z-Index placement in CreateJS

I'm struggling to adjust the z-index for my line Graphic(). My goal is to ensure that the line always appears behind the other two shapes. Based on my understanding, the first element added has a z-index of 0, the second one has a z-index of 1, and s ...

I'm having trouble with my code not fitting all screen resolutions. I usually code on a Macbook, but recently switched to a Windows computer and now everything is out of whack

$(function(){ $("#Welcome").typed({ strings: ["PROGRAMMERS / NETWORKERS"], typeSpeed: 60 }); }); html { background-color: mintcream; background-size: 100%; } /* Home */ .homeheader button { background-color: #4CAF450; top: ...

Media query failing to adjust properly

On my website's "about" page, I'm attempting to implement a media query but encountering an issue. In the original CSS, I structured the "information" section into 2 columns with right padding to prevent the content from extending all the way to ...