Home > Software engineering >  How to place an icon before a text?
How to place an icon before a text?

Time:11-08

I want to place an icon before the "Mon compte" text on my website.

Here is my HTML code :

<a href="/user"  data-drupal-link-system-path="user">
  Mon compte
</a>

Here is my CSS code :

#block-useraccountmenu a::before {
    content: "";
    display: block;
    background: url("/themes/subtheme_olivero/images/person-circle.svg?itok=5") no-repeat;
    width: 28px;
    height: 28px;
    float: left;
    margin: 0 6px 0 0;
}

It works fine, here is the output :

enter image description here

My problem is that when I right click on the link, the icon is positioned in the middle of the text. I don't understand why the rendering changes like this :

enter image description here

If I click next to it, the icon repositions correctly. How to correct this problem ? What's wrong with my CSS code ? Thanks

https://www.cocorinet.fr/

UPDATE

If I apply the CSS to "a" the icon centers over the text, when right clicking on the text.

If I apply CSS to "li" it works fine, but I want the face icon to be part of the link.

Small clarification, I can't modify the HTML code and I don't want to use an external library for a single icon.

CodePudding user response:

Perhaps it might be easier to use Font Awesome. First insert the CDN:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css"/>

Then head over to their icon page and select an icon (Make sure it's not a 'pro' icon). It seems like this is the one you are going for:

<i ></i>

After that, it's easy. Just paste that line (or a different icon) before your text:

<a href="/user"  data-drupal-link-system-path="user">
  <i ></i> Mon compte
</a>

That's it! You might need to style it using font-size and other rules.

Edit:

The most you can reduce the content of the CDN is like this:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/fontawesome.min.css"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/solid.min.css"/>

Although this method has 2 URLs, its much better than the first method.

CodePudding user response:

Instead of using a background image, you can try using the img element instead. Code would look like this.

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">

<style>
body {font-family: Arial, Helvetica, sans-serif;}
* {box-sizing: border-box;}

.input-container {
  display: -ms-flexbox; /* IE10 */
  display: flex;
  width: 100%;
  margin-bottom: 15px;
}

.input-field {
  width: 100%;
  padding: 10px;
  outline: none;
  text-align: left;
}

</style>
</head>
<body>

  <div >
    <img src="img_girl.jpg" alt="Girl in a jacket" width="50" height="60">
    <div > Mon compte </div>
  </div>

</body>
</html>
  • Related