Achieving perfect alignment: Centering text within a div with an aspect ratio

I have encountered a situation where I need to center text within a div that also has an aspect ratio. Since the aspect-ratio property is not supported by major browsers like Safari, I am looking for an alternative solution.

Here is my current code:

.aspect-ratio-div{
   background-color: #f2f2f7;
   position: relative;
   width: 100%;
   padding-top: 33.33%;
}

.text{
    position:  absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    text-align: center;
    font-size: 20px;
    color: white;
}
<html>
  <div class="aspect-ratio-div">
    <label>This is some centered text</label>
  </div>
</html>

This method works well for images, but how can I achieve the same effect for text?

I want the output to resemble this image: https://i.sstatic.net/Kjm9M.png

The white space should maintain a 1:3 ratio, with the text always centered within it.

Any suggestions for a better approach?

I found the solution I needed, thank you!

Answer №1

There are a couple of ways to achieve this. Here are two options.

.text utilizes display: flex; for alignment
.text-absolute relies solely on absolute positioning

.aspect-ratio-div{
   background-color: #f2f2f7;
   position: relative;
   width: 100%;
   padding-top: 33.33%;
}

.text{
    position:  absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    font-size: 20px;
    color: black;
}

.text-absolute {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 20px;
  color: black;
}
<html>
  <div class="aspect-ratio-div">
    <label class="text-absolute">This is some centered text</label>
  </div>
</html>

Answer №2

Ensure to update your class to label as you have used label in HTML and make necessary adjustments in CSS

.aspect-ratio-div{
   background-color: #f2f2f7;
   position: relative;
   width: 100%;
   padding-top: 33.33%;
}

label{
    position:  absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
    font-size: 20px;
    color: #000;
}
<html>
  <div class="aspect-ratio-div">
    <label>This is some centered text</label>
  </div>
</html>

Answer №3

After modifying your code, here is the updated result that utilizes Flex instead of transform to achieve the desired outcome. This approach will ensure proper display of multiline texts if necessary.

.aspect-ratio-div{
   background-color: #f2f2f7;
   position: relative;
   width: 100%;
   padding-top: 33.33%;
}

.text {
    position:  absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    font-size: 20px;
    color: #000;
}
<html>
  <div class="aspect-ratio-div">
    <label class="text">This is some centered text</label>
  </div>
</html>

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

Verifying the accessibility of a website using JQuery/Javascript

I am attempting to use JavaScript to ping a website and display the result. Unfortunately, I have not had any success with this JSFiddle: https://jsfiddle.net/yyjowtru/ Although I believe I am close to achieving the desired outcome, changing the URL in t ...

Displaying photos locally in HTML is not supported

I've encountered an issue with my HTML code. I'm trying to load images from my local drive, and the path to the folder seems correct because I can open the images by ctrl + clicking on them. However, when I open my page using a live server or hos ...

InvalidTypeError: The function 'state.map' cannot be applied

import React from "react"; import { useContext, useEffect, useRef, useState } from "react"; import noteContext from "../Context/notes/NoteContext"; import Addnote from "./Addnote"; import Noteitems from "./Notei ...

Simple Steps to Connect an HTML File to CSS in Windows Notepad

I have scoured the depths of the online realm in search of a method to connect HTML with CSS within the preinstalled Notepad application on Windows. Regrettably, my attempts, including utilizing the system path, proved fruitless. Is it conceivable to ach ...

Adjust the child element's value by referencing the parent class name

I need to update the content of child elements within an HTML file based on the class name of their parent element, using JavaScript. While I have successfully achieved this for static values by creating a TreeWalker for text nodes, doing the same for dyn ...

Updating a column in a SQL Table via an Ajax request

I am attempting to store the on or off value from a form into an SQL database by calling a JS function with an AJAX request that sends it to a PHP page for processing. I seem to be facing some issues with my code and could really use some assistance as the ...

Ways to access and delete the canvas using ref steps?

Having a canvas in a react component, I utilized react refs to access the node and implemented a destroy() method. However, I encountered an error: TypeError: canvasRef.current.destroy is not a function How can we properly access the node (canvas) using r ...

JavaScript Code for Executing Function on Checkbox Checked/Unchecked

My goal is to display an image when the checkbox is checked and show text when it is unchecked. However, I am facing an issue where the text does not appear when I uncheck the checkbox. <input type="checkbox" id="checkword" onchang ...

Implementing timeAgo with jQuery (or a similar tool) to display the elapsed time since a user (client) accesses or updates a webpage

https://i.sstatic.net/Y7bzO.png Currently, the timer displayed always shows the actual time instead of phrases like "about a minute ago" or "5 minutes ago". I have tried different solutions without success. //timeago by jQuery (function timeAgo(selector) ...

Height of the div dynamically increases upwards

Just a quick question - is there a way to make position: fixed divs at the bottom of an element (such as the body) grow upwards as content is dynamically added? Maybe something like anchor: bottom or increase: up? I'm thinking that using JavaScript m ...

employing the `useSWR` mutation with an `undefined` parameter does not trigger revalidation in

I am utilizing uswSWR for managing user authentication: export function useAuthenticatedUser() { const { data, error, isLoading, mutate } = useSWR("user", UserApi.getAuthenticatedUser, { shouldRetryOnError(err) { ...

What is the best way to prevent 2 divs from overlapping on a webpage?

I'm having trouble getting the smaller div to display right below the larger red div. I tried using the display block css property, but it doesn't seem to be working as expected. Unfortunately, I can't provide an image here, but you can vie ...

Angular Oops! We ran into a small hiccup: [$injector:modulerr]

I am facing an issue with an angular js error angular.js:36 Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.2.19/$injector/modulerr?p0=app&p1=Error%3A%20…gleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.19%2Fangular.min.js%3A18%3A139) ...

What is the best way to define a named, optional parameter in TypeScript-React that can accept an object with optional fields and default values?

Is there a way to achieve something similar to the style property found in default HTML components? For instance: <div ref={ref} style={{ overflow: 'visible', height: 600, width: '100%' }}> The style prop is optional, and the fie ...

Learn the method to display a particular post using its unique post ID

I need some help displaying two specific posts by utilizing their post IDs. I'm struggling with the code to retrieve and call these post IDs. Can someone assist me? /////////////////////////////// ////////////////////////////// <div class="foo ...

Moving from CSS to SCSS: Incorporating CSS files from npm packages - A Step-by-Step Guide

I am new to SASS and currently in the process of converting my existing project's CSS files to SCSS. I know that simply changing the extension to .scss will work for my custom files, but I'm not sure how to handle the dependency style files. I ty ...

The like button animation works perfectly for individual posts, but for multiple posts, only the like button on the first post

Having an issue with the like button code on a single news feed. The button works for the first post, but when clicking on other posts, it only affects the first post button. I am using post UI and looping the UI based on the total post count without Javas ...

What causes npm to be undefined when I verify node?

screenshot of my terminal Currently learning react and encountered an issue while checking if npm downloaded properly. It appears to be running fine, but for some reason, after I enter 'node' and then try to check npm again, I get an error messa ...

I need assistance in utilizing my PHP variable UserNameID to remove the specific user's row from the database

I want to give users the option to delete their account from the database with a simple button click on my php forum. See the code snippet below: <div class="btn-group"> <button style="width:200px" type="button" class="btn btn-primary"> ...

Struggling to Fetch Data from REST API with ng-repeat in Angular JS

After making a REST call from Angular JS and receiving a response from the API, I am looking to display messages on the front end using ng-repeat in my controller. $http({ url: "http://localhost:8080/services/AddConfig", method: "POS ...