Home > Web Front-end > CSS Tutorial > How Can I Center Text Over an Image Using CSS Positioning Instead of Flexbox?

How Can I Center Text Over an Image Using CSS Positioning Instead of Flexbox?

Susan Sarandon
Release: 2024-12-20 00:50:09
Original
478 people have browsed it

How Can I Center Text Over an Image Using CSS Positioning Instead of Flexbox?

Centering Text Over an Image Using Flexbox

In this guide, we will explore an alternative approach to centering text over an image using pure CSS positioning properties instead of Flexbox.

Positioning Properties:

.height-100vh {
  position: relative;
}

.text {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
Copy after login
  1. Establishing the Relative Parent: We set position: relative on the container element with height-100vh class to establish a positioned ancestor for absolute positioning.
  2. Absolutely Positioning the Text: We use position: absolute on the .text class to position it outside the normal document flow.
  3. Horizontal Alignment: By setting left: 50%, we center the text horizontally by measuring it from the left edge of the container.
  4. Vertical Alignment: Similarly, top: 50% vertically centers the text by measuring it from the top edge of the container.
  5. Precise Centering: To precisely center the text, we apply transform: translate(-50%, -50%). This translates the text by -50% in both directions, ultimately shifting it to the center.

Example Usage:

<section class="height-100vh center-aligned">
  <img class="background-image" src="image.jpg" />
  <div class="text">SOME TEXT</div>
</section>
Copy after login

By implementing these positioning properties, you can effectively center text over an image without relying on Flexbox. This approach offers a simple and straightforward solution for this common layout task.

The above is the detailed content of How Can I Center Text Over an Image Using CSS Positioning Instead of Flexbox?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template