search
HomeWeb Front-endCSS TutorialHow to achieve text icon alignment with css

How to achieve text icon alignment with css

Apr 20, 2020 am 09:12 AM
cssicontext

How to achieve text icon alignment with css

In development, it is most common to see pictures and text displayed on one line. The alignment of two in-line elements is usually the most troublesome. Sometimes the most commonly used Alignment method, but there are always some deviations. Let’s take a look at the most basic example:

html part:

<div class="wrap">
    <img src="/static/imghwm/default1.png"  data-src="https://avatars3.githubusercontent.com/u/16339041?s=60&v=4"  class="lazy"   alt="">
    xx测试对齐Style-
</div>

Recommended tutorial: CSS introductory tutorial

css part:

.wrap {
      width: 300px;
      text-align: center;
      margin: 20px auto;
      font-size: 14px;
 }
 .wrap img {
      width: 20px;
 }

The effect of not using alignment is as follows:

How to achieve text icon alignment with css

The default alignment is baseline, also It's the bottom line of the x letter.

This also answers the first question. When the browser's images and text are not additionally set, they are based on the lower edge of the lowercase letter x, which is vertical-align:baseline;.

Several common centering solutions

1. Use vertical-align center alignment

.wrap {
    vertical-align: middle;
    }
.wrap img {
    vertical-align: middle;
}

When we use the commonly used vertical-align to align text and pictures, it is actually the same There is a certain deviation, as shown below: The middle value of

How to achieve text icon alignment with css

vertical-align is actually relative to half the height of the lowercase letter x, so the picture will follow x start to align in the middle, but for other characters such as S and Chinese, you will find that there will be a slight deviation anyway, and the picture will be relatively lower.

2. Use vertical-align and span to wrap the text.

Let’s make a slight change and wrap the text part with a span tag, and use vertical-align: middle; style alignment for the span. . You will find that the picture moves up a little at this time.

The effect is as follows:

How to achieve text icon alignment with css

3. Use flex layout

display: flex;
align-items: center;

How to achieve text icon alignment with css

But even if it is flex layout , sometimes there will be a slight deviation, for example: the image size is an even number, the font-size is an even number, the line-height is aligned when it is an even number; when it is an odd number, it is 1px higher.

4. Use the ex unit

ex is the height of the lowercase letter x, which can be used for the vertical center alignment effect of inline elements that are not affected by fonts and font sizes.

PS: However, this is very practical when the height of the icon is the same as the text. For example, if an arrow is added after the character (click to expand).

.wrap img {
    height: 1ex;
}

5. Use of vertical-align numerical method

vertical-align attribute value can use numerical type and percentage value. For example, it is still the basic case above: if the image height is 20px, When the text font-size is 22px, the default alignment is the baseline of the text, so the image will be 2px upward. At this time, you only need to offset the image 2px downward to achieve the alignment effect, and the numerical value of the vertical-align attribute has Very good compatibility.

.wrap {
            width: 100%;
            padding-top: 200px;
            text-align: center;
            margin: 20px auto;
            font-size: 22px;
            height: 40px;
            
        }
        .wrap img {
            width: 20px;
            vertical-align: -2px;
        }

Recommended related video tutorials: css video tutorial

The above is the detailed content of How to achieve text icon alignment with css. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:脚本之家. If there is any infringement, please contact admin@php.cn delete
This Isn't Supposed to Happen: Troubleshooting the ImpossibleThis Isn't Supposed to Happen: Troubleshooting the ImpossibleMay 15, 2025 am 10:32 AM

What it looks like to troubleshoot one of those impossible issues that turns out to be something totally else you never thought of.

@keyframes vs CSS Transitions: What is the difference?@keyframes vs CSS Transitions: What is the difference?May 14, 2025 am 12:01 AM

@keyframesandCSSTransitionsdifferincomplexity:@keyframesallowsfordetailedanimationsequences,whileCSSTransitionshandlesimplestatechanges.UseCSSTransitionsforhovereffectslikebuttoncolorchanges,and@keyframesforintricateanimationslikerotatingspinners.

Using Pages CMS for Static Site Content ManagementUsing Pages CMS for Static Site Content ManagementMay 13, 2025 am 09:24 AM

I know, I know: there are a ton of content management system options available, and while I've tested several, none have really been the one, y'know? Weird pricing models, difficult customization, some even end up becoming a whole &

The Ultimate Guide to Linking CSS Files in HTMLThe Ultimate Guide to Linking CSS Files in HTMLMay 13, 2025 am 12:02 AM

Linking CSS files to HTML can be achieved by using elements in part of HTML. 1) Use tags to link local CSS files. 2) Multiple CSS files can be implemented by adding multiple tags. 3) External CSS files use absolute URL links, such as. 4) Ensure the correct use of file paths and CSS file loading order, and optimize performance can use CSS preprocessor to merge files.

CSS Flexbox vs Grid: a comprehensive reviewCSS Flexbox vs Grid: a comprehensive reviewMay 12, 2025 am 12:01 AM

Choosing Flexbox or Grid depends on the layout requirements: 1) Flexbox is suitable for one-dimensional layouts, such as navigation bar; 2) Grid is suitable for two-dimensional layouts, such as magazine layouts. The two can be used in the project to improve the layout effect.

How to Include CSS Files: Methods and Best PracticesHow to Include CSS Files: Methods and Best PracticesMay 11, 2025 am 12:02 AM

The best way to include CSS files is to use tags to introduce external CSS files in the HTML part. 1. Use tags to introduce external CSS files, such as. 2. For small adjustments, inline CSS can be used, but should be used with caution. 3. Large projects can use CSS preprocessors such as Sass or Less to import other CSS files through @import. 4. For performance, CSS files should be merged and CDN should be used, and compressed using tools such as CSSNano.

Flexbox vs Grid: should I learn them both?Flexbox vs Grid: should I learn them both?May 10, 2025 am 12:01 AM

Yes,youshouldlearnbothFlexboxandGrid.1)Flexboxisidealforone-dimensional,flexiblelayoutslikenavigationmenus.2)Gridexcelsintwo-dimensional,complexdesignssuchasmagazinelayouts.3)Combiningbothenhanceslayoutflexibilityandresponsiveness,allowingforstructur

Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)May 09, 2025 am 09:57 AM

What does it look like to refactor your own code? John Rhea picks apart an old CSS animation he wrote and walks through the thought process of optimizing it.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment