Как изменить текст html через css

How can I replace text with CSS using a method like this: .pvw-title img[src*="IKON.img"] { visibility:hidden; } Instead of ( img[src*="IKON.img"] ), I need to use something that can replace t...

How can I replace text with CSS using a method like this:

.pvw-title img[src*="IKON.img"] { visibility:hidden; }

Instead of ( img[src*="IKON.img"] ), I need to use something that can replace text instead.

I have to use [ ] to get it to work.

<div class="pvw-title">Facts</div>

I need to replace «Facts«.

Penny Liu's user avatar

Penny Liu

13.8k5 gold badges74 silver badges91 bronze badges

asked Oct 25, 2011 at 21:58

MokiTa's user avatar

4

Or maybe you could wrap ‘Facts’ round a <span> as follows:

.pvw-title span {
  display: none;
}
.pvw-title:after {
  content: 'whatever it is you want to add';
}
<div class="pvw-title"><span>Facts</span></div>

Abrar Jahin's user avatar

Abrar Jahin

13.7k23 gold badges108 silver badges158 bronze badges

answered Dec 18, 2012 at 21:03

Matthew Cachia's user avatar

Matthew CachiaMatthew Cachia

4,3361 gold badge13 silver badges16 bronze badges

10

Obligatory: This is a hack: CSS isn’t the right place to do this, but in some situations — eg, you have a third party library in an iframe that can only be customized by CSS — this kind of hack is the only option.

You can replace text through CSS. Let’s replace a green button that has the word ‘hello’ with a red button that has the word ‘goodbye’, using CSS.

Before:

enter image description here

After:

enter image description here

See http://jsfiddle.net/ZBj2m/274/ for a live demo:

Here’s our green button:

<button>Hello</button>

button {
  background-color: green;
  color: black;
  padding: 5px;
}

Now let’s hide the original element, but add another block element afterwards:

button {
  visibility: hidden;
}
button:after {
  content:'goodbye'; 
  visibility: visible;
  display: block;
  position: absolute;
  background-color: red;
  padding: 5px;
  top: 2px;
}

Note:

  • We explicitly need to mark this as a block element, ‘after’ elements are inline by default
  • We need to compensate for the original element by adjusting the pseudo-element’s position.
  • We must hide the original element and display the pseudo element using visibility. Note display: none on the original element doesn’t work.

answered Jan 10, 2013 at 15:55

mikemaccana's user avatar

mikemaccanamikemaccana

103k93 gold badges372 silver badges470 bronze badges

9

If you’re willing to use pseudo elements and let them insert content, you can do the following. It doesn’t assume knowledge of the original element and doesn’t require additional markup.

.element {
  text-indent: -9999px;
  line-height: 0; /* Collapse the original line */
}

.element::after {
  content: "New text";
  text-indent: 0;
  display: block;
  line-height: initial; /* New content takes up original line height */
}

JSFiddle Example

answered Feb 26, 2014 at 22:14

James van Dyke's user avatar

James van DykeJames van Dyke

4,6903 gold badges27 silver badges25 bronze badges

10

Based on
mikemaccana’s answer,
this worked for me

button {
  position: absolute;
  visibility: hidden;
}

button:before {
  content: "goodbye";
  visibility: visible;
}
<button>original</button>

§ Absolute positioning

an element that is positioned absolutely is taken out of the flow and thus
takes up no space when placing other elements.

Flimm's user avatar

Flimm

129k44 gold badges244 silver badges254 bronze badges

answered Jun 18, 2013 at 3:51

Zombo's user avatar

1

This is simple, short, and effective. No additional HTML is necessary.

.pvw-title { color: transparent; }

.pvw-title:after {
        content: "New Text To Replace Old";
        color: black; /* set color to original text color */
        margin-left: -30px;
        /* margin-left equals length of text we're replacing */
    }

I had to do this for replacing link text, other than home, for WooCommerce breadcrumbs

Sass/Less

body.woocommerce .woocommerce-breadcrumb > a[href$="/shop/"] {
    color: transparent;
    &:after {
        content: "Store";
        color: grey;
        margin-left: -30px;
    }
}

CSS

body.woocommerce .woocommerce-breadcrumb > a[href$="/shop/"] {
    color: transparent;
}

body.woocommerce .woocommerce-breadcrumb > a[href$="/shop/"]&:after {
    content: "Store";
    color: @child-color-grey;
    margin-left: -30px;
}

Peter Mortensen's user avatar

answered Apr 16, 2015 at 18:16

9ete's user avatar

9ete9ete

3,6421 gold badge34 silver badges32 bronze badges

You can’t, well, you can.

.pvw-title:after {
  content: "Test";
}

This will insert content after the current content of the element. It doesn’t actually replace it, but you can choose for an empty div, and use CSS to add all the content.

But while you more or less can, you shouldn’t. Actual content should be put in the document. The content property is mainly intended for small markup, like quotation marks around text that should appear quoted.

answered Oct 25, 2011 at 22:02

GolezTrol's user avatar

GolezTrolGolezTrol

113k17 gold badges182 silver badges207 bronze badges

3

In order to use after and hide the original content, you can use this hack:

.pvw-title {
  font-size: 0;
}
.pvw-title:after {
  font-size: 1rem;
  content: 'I am a totally different piece of text!';
}
<div class="pvw-title">Facts</div>

Setting font-size to 0 makes the text disappear without removing the actual element from the viewport. Therefore, the :after selector works and should show on all browsers.

answered Jun 29, 2021 at 22:42

Thatkookooguy's user avatar

ThatkookooguyThatkookooguy

6,5191 gold badge31 silver badges53 bronze badges

Try using :before and :after. One inserts text after HTML is rendered, and the other inserts before HTML is rendered. If you want to replace text, leave button content empty.

This example sets the button text according to the size of the screen width.

<meta name="viewport" content="width=device-width, initial-scale=1">

<style>
  button:before {
    content: 'small screen';
  }
  @media screen and (min-width: 480px) {
    button:before {
      content: 'big screen';
    }
  }
</style>
<body>
  <button type="button">xxx</button>
  <button type="button"></button>
</body>

Button text:

  1. With :before

    big screenxxx

    big screen

  2. With :after

    xxxbig screen

    big screen

Peter Mortensen's user avatar

answered Sep 12, 2016 at 17:14

live-love's user avatar

live-lovelive-love

46.3k22 gold badges228 silver badges197 bronze badges

I had better luck setting the font-size: 0 of the outer element, and the font-size of the :after selector to whatever I needed.

answered Mar 3, 2017 at 16:34

jerome's user avatar

jeromejerome

4,70913 gold badges52 silver badges70 bronze badges

2

If you just want to show different texts or images, keep the tag empty and write your content in multiple data attributes like that <span data-text1="Hello" data-text2="Bye"></span>.
Display them with one of the pseudo classes :before {content: attr(data-text1)}

Now you have a bunch of different ways to switch between them. I used them in combination with media queries for a responsive design approach to change the names of my navigation to icons.

jsfiddle demonstration and examples

It may not perfectly answer the question, but it satisfied my needs and maybe others too.

Peter Mortensen's user avatar

answered Aug 7, 2016 at 10:26

Robbendebiene's user avatar

RobbendebieneRobbendebiene

3,8453 gold badges26 silver badges32 bronze badges

Text replacement with pseudo-elements and CSS visibility

HTML

<p class="replaced">Original Text</p>

CSS

.replaced {
    visibility: hidden;
    position: relative;
}

.replaced:after {
    visibility: visible;
    position: absolute;
    top: 0;
    left: 0;
    content: "This text replaces the original.";
}

Community's user avatar

answered Aug 16, 2018 at 0:25

Ahsan Aftab's user avatar

Ahsan AftabAhsan Aftab

1812 silver badges6 bronze badges

The simplest way I found is by making the element font-size: 0px, then overwrite it with any font size when creating :after pseudo. Example below:

.pvw-title { 
    font-size:0px;
}

.pvw-title:after {
        content: "Hello";
        font-size:15px !important;
}

answered Feb 26, 2021 at 19:44

ASammour's user avatar

ASammourASammour

8179 silver badges12 bronze badges

This worked for me with inline text. It was tested in Firefox, Safari, Chrome, and Opera.

<p>Lorem ipsum dolor sit amet, consectetur <span>Some Text</span> adipiscing elit.</p>

span {
    visibility: hidden;
    word-spacing: -999px;
    letter-spacing: -999px;
}

span:after {
    content: "goodbye";
    visibility: visible;
    word-spacing: normal;
    letter-spacing: normal;
}

Peter Mortensen's user avatar

answered Aug 2, 2013 at 22:39

Noel Williams's user avatar

1

I use this trick:

.pvw-title {
    text-indent: -999px;
}
.pvw-title:after {
    text-indent: 0px;
    float: left;
    content: 'My New Content';
}

I’ve even used this to handle internationalization of pages by just changing a base class…

.translate-es .welcome {
    text-indent: -999px;
}
.translate-es .welcome:after {
    text-indent: 0px;
    float: left;
    content: '¡Bienvenidos!';
}

answered Jul 5, 2015 at 12:16

Pete OK's user avatar

Pete OKPete OK

1191 silver badge3 bronze badges

1

Try this way:

IDENTIFIER {
    visibility: hidden;
    position: relative;
}
IDENTIFIER::after {
    visibility: visible;
    position: absolute;
    top: 0;
    left: 0;
    content: "NEW_CONTENT";
}

answered Aug 31, 2021 at 1:45

Murtaza JAFARI's user avatar

1

This implements a checkbox as a button which shows either Yes or No depending on its ‘checked’ state. So it demonstrates one way of replacing text using CSS without having to write any code.

It will still behave like a checkbox as far as returning (or not returning) a POST value, but from a display point of view it looks like a toggle button.

The colours may not be to your liking, they’re only there to illustrate a point.

The HTML is:

<input type="checkbox" class="yesno" id="testcb" /><label for="testcb"><span></span></label>

…and the CSS is:

/* --------------------------------- */
/* Make the checkbox non-displayable */
/* --------------------------------- */
input[type="checkbox"].yesno {
    display:none;
}
/* --------------------------------- */
/* Set the associated label <span>   */
/* the way you want it to look.      */
/* --------------------------------- */
input[type="checkbox"].yesno+label span {
    display:inline-block;
    width:80px;
    height:30px;
    text-align:center;
    vertical-align:middle;
    color:#800000;
    background-color:white;
    border-style:solid;
    border-width:1px;
    border-color:black;
    cursor:pointer;
}
/* --------------------------------- */
/* By default the content after the  */
/* the label <span> is "No"          */
/* --------------------------------- */
input[type="checkbox"].yesno+label span:after {
    content:"No";
}
/* --------------------------------- */
/* When the box is checked the       */
/* content after the label <span>    */
/* is "Yes" (which replaces any      */
/* existing content).                */
/* When the box becomes unchecked the*/
/* content reverts to the way it was.*/
/* --------------------------------- */
input[type="checkbox"].yesno:checked+label span:after {
    content:"Yes";
}
/* --------------------------------- */
/* When the box is checked the       */
/* label <span> looks like this      */
/* (which replaces any existing)     */
/* When the box becomes unchecked the*/
/* layout reverts to the way it was. */
/* --------------------------------- */
input[type="checkbox"].yesno:checked+label span {
    color:green;
    background-color:#C8C8C8;
}

I’ve only tried it on Firefox, but it’s standard CSS so it ought to work elsewhere.

answered Nov 12, 2015 at 15:05

Steve Douglas's user avatar

Using a pseudo element, this method doesn’t require knowledge of the original element and doesn’t require any additional markup.

#someElement{
    color: transparent; /* You may need to change this color */
    position: relative;
}
#someElement:after { /* Or use :before if that tickles your fancy */
    content: "New text";
    color: initial;
    position: absolute;
    top: 0;
    left: 0;
}

Peter Mortensen's user avatar

answered May 16, 2015 at 17:08

Vin's user avatar

VinVin

1,6254 gold badges26 silver badges33 bronze badges

I had an issue where I had to replace the text of link, but I couldn’t use JavaScript nor could I directly change the text of a hyperlink as it was compiled down from XML. Also, I couldn’t use pseudo elements, or they didn’t seem to work when I had tried them.

Basically, I put the text I wanted into a span and put the anchor tag underneath it and wrapped both in a div. I basically moved the anchor tag up via CSS and then made the font transparent. Now when you hover over the span, it «acts» like a link. A really hacky way of doing this, but this is how you can have a link with different text…

This is a fiddle of how I got around this issue

My HTML

<div class="field">
    <span>This is your link text</span><br/>
    <a href="//www.google.com" target="_blank">This is your actual link</a>
</div>

My CSS

 div.field a {
     color: transparent;
     position: absolute;
     top:1%;
 }
 div.field span {
     display: inline-block;
 }

The CSS will need to change based off your requirements, but this is a general way of doing what you are asking.

Peter Mortensen's user avatar

answered Mar 21, 2015 at 20:48

AlmightyWhy's user avatar

AlmightyWhyAlmightyWhy

4666 silver badges11 bronze badges

1

I found a solution like this where a word, «Dark», would be shortened to just «D» on a smaller screen width. Basically you just make the font size of the original content 0 and have the shortened form as a pseudo element.

In this example the change happens on hover instead:

span {
  font-size: 12px;
}

span:after {
  display: none;
  font-size: 12px;
  content: 'D';
  color: red;
}

span:hover {
  font-size: 0px;
}

span:hover:after {
  display: inline;
}
<span>Dark</span>

Peter Mortensen's user avatar

answered Dec 28, 2019 at 21:11

StefanBob's user avatar

StefanBobStefanBob

4,7522 gold badges31 silver badges38 bronze badges

After eight years, I faced the same challenge when trying to use the Stylish browser extension to change something on a website (not mine). And this time I made it work by looking at the source code using «inspect element» and created the CSS code based on that.

This it what it looked like before:

<table>
  <tbody>
    <tr>
      <td role="gridcell">
        <span title="In progress" style="background-color: #e2047a;color:White;margin:2px;border-radius:2px;padding-left: 2px; padding-right: 2px;text-align: center;width: 45px; display: block;overflow: hidden;text-overflow: ellipsis;">In progress</span>
      </td>
    </tr>
  </tbody>
</table>

This is the same piece of the HTML and the CSS I used to modify the style:

td span[style="background-color: #e2047a;color:White;margin:2px;border-radius:2px;padding-left: 2px; padding-right: 2px;text-align: center;width: 45px; display: block;overflow: hidden;text-overflow: ellipsis;"] {
  width: 100px!important;
}
<table>
  <tbody>
    <tr>
      <td role="gridcell">
        <span title="In progress" style="background-color: #e2047a;color:White;margin:2px;border-radius:2px;padding-left: 2px; padding-right: 2px;text-align: center;width: 45px; display: block;overflow: hidden;text-overflow: ellipsis;">In progress</span>
      </td>
    </tr>
  </tbody>
</table>

You can run the code above and you will see that it works (tested in Chrome).


This is simply what I wanted back in the days when I asked this question.

I was using some sort of community blog/Myspace similar stuff and the only thing you had when styling your profile was their CSS editor, and that’s why I wanted to select it based on the style.

I found the answer here:

  • Advanced CSS Selector — Select based on styling

  • CSS selector by inline style attribute

Peter Mortensen's user avatar

answered Jan 2, 2020 at 11:26

MokiTa's user avatar

MokiTaMokiTa

4,5903 gold badges15 silver badges16 bronze badges

Unlike what I see in every single other answer, you don’t need to use pseudo elements in order to replace the content of a tag with an image

<div class="pvw-title">Facts</div>

    div.pvw-title { /* No :after or :before required */
        content: url("your URL here");
    }

answered Jul 21, 2017 at 23:43

Estecka's user avatar

EsteckaEstecka

3781 silver badge15 bronze badges

2

Well, as many said this is a hack. However, I’d like to add more up-to-date hack, which takes an advantage of flexbox and rem, i.e.

  • You don’t want to manually position this text to be changed, that’s why you’d like to take an advantage of flexbox
  • You don’t want to use padding and/or margin to the text explicitly using px, which for different screen sizes on different devices and browsers might give different output

Here’s the solution, in short flexbox makes sure that it’s automatically positioned perfectly and rem is more standardized (and automated) alternative for pixels.

CodeSandbox with code below and output in a form of a screenshot, do please read a note below the code!

h1 {
  background-color: green;
  color: black;
  text-align: center;
  visibility: hidden;
}
h1:after {
  background-color: silver;
  color: yellow;
  content: "This is my great text AFTER";
  display: flex;
  justify-content: center;
  margin-top: -2.3rem;
  visibility: visible;
}
h1:before {
  color: blue;
  content: "However, this is a longer text to show this example BEFORE";
  display: flex;
  justify-content: center;
  margin-bottom: -2.3rem;
  visibility: visible;
}

Note: for different tags you might need different values of rem, this one has been justified for h1 and only on large screens. However with @media you could easily extend this to mobile devices.

A hack how to replace HTML text using CSS

answered Jun 12, 2020 at 20:38

Daniel Danielecki's user avatar

Example

<!DOCTYPE html>
<html> 
<head> 
   <title>Devnote</title>
    <style>
        .replacedValue { 
            visibility: hidden; 
            position: relative; 
        } 
        .replacedValue:after { 
            visibility: visible; 
            position: absolute; 
            top: 0; 
            left: 0; 
            content: "Devnote is developer answer solve. devnote.in"; 
        } 
    </style> 
</head>
<body> 
    <p class="replacedValue">Old Text Here</p>
</body> 
</html>

Output

Devnote is developer answer solve. devnote.in

answered Dec 9, 2020 at 11:07

Fefar Ravi's user avatar

Fefar RaviFefar Ravi

7087 silver badges17 bronze badges

This isn’t really possible without tricks. Here is a way that works by replacing the text with an image of text.

.pvw-title{
    text-indent: -9999px;
    background-image: url(text_image.png)
}

This type of thing is typically done with JavaScript. Here is how it can be done with jQuery:

$('.pvw-title').text('new text');

Peter Mortensen's user avatar

answered Oct 25, 2011 at 22:06

Nathan Manousos's user avatar

Nathan ManousosNathan Manousos

13k2 gold badges27 silver badges37 bronze badges

4

The way to make this work is to add line-height to the CSS content. This will make the block to be seen above the hidden, thus this will not hide the changed text.

Example with use before:

.pvw-title span {
  display: none;
}

.pvw-title:before {
  content: 'Whatever it is you want to add';
  line-height: 1.5em
}

Peter Mortensen's user avatar

answered Jan 2, 2019 at 10:25

Tal Talmon's user avatar

Replacing a text is mostly worked out on the server side. But in some circumstances, where we don’t have control over the server, or we are working under restrictions, replacing text using CSS may be a choice.
Method 1: Using Pseudo Elements and Visibility Modifier with Absolute Positioning 
To start with, we wrap the text and assign it a class. This method requires very little markup.

<p class="toBeReplaced">Old Text</p>

The text “Old Text” needs to be hidden first and a new text has to be positioned exactly where the old text was. To do so, we change the visibility of this text using CSS to hidden first.

.toBeReplaced {
    visibility: hidden;
    position: relative;
}

Then we add a new text at the exact same position, using the pseudo elements and corresponding explicit positioning.

.toBeReplaced:after {
    visibility: visible;
    position: absolute;
    top: 0;
    left: 0;
    content: "This text replaces the original.";
}

Note that after is the pseudo element in use here. We use the visibility modifier once again to show the new text. The content attribute contains the new text.
Example:

<html>

<head>

    <style>

        .toBeReplaced {

            visibility: hidden;

            position: relative;

        }

        .toBeReplaced:after {

            visibility: visible;

            position: absolute;

            top: 0;

            left: 0;

            content: "This text replaces the original.";

        }

    </style>

</head>

<body>

    <p class="toBeReplaced">Old Text</p>

</body>

</html>

Output:

This text replaces the original.

Method 2: Using Pseudo Elements and Visibility Modifier with <span> tag 
In this method, we need a little bit more markup but we no longer need to specify any absolute positioning for our new text. We wrap the text using <span> tags.

<p class="toBeReplaced"><span>Old Text</span></p>

In this method, we use a child element to wrap the text, that is, the text is now inside <p> and <span> tags. So we can use the display: none CSS attribute to hide the text in the <span> element. Then we can simply replace the text as we did in the previous method, without specifying any positioning.

.toBeReplaced span {
    display: none;
}

.toBeReplaced:after {
    content: "This text replaces the original.";
}

Example:

<html>

<head>

    <style>

        .toBeReplaced span {

            display: none;

        }

        .toBeReplaced:after {

            content: "This text replaces the original.";

        }

    </style>

</head>

<body>

    <p class="toBeReplaced"><span>Old Text</span></p>

</body>

</html>

Output:

This text replaces the original.

CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.

Replacing a text is mostly worked out on the server side. But in some circumstances, where we don’t have control over the server, or we are working under restrictions, replacing text using CSS may be a choice.
Method 1: Using Pseudo Elements and Visibility Modifier with Absolute Positioning 
To start with, we wrap the text and assign it a class. This method requires very little markup.

<p class="toBeReplaced">Old Text</p>

The text “Old Text” needs to be hidden first and a new text has to be positioned exactly where the old text was. To do so, we change the visibility of this text using CSS to hidden first.

.toBeReplaced {
    visibility: hidden;
    position: relative;
}

Then we add a new text at the exact same position, using the pseudo elements and corresponding explicit positioning.

.toBeReplaced:after {
    visibility: visible;
    position: absolute;
    top: 0;
    left: 0;
    content: "This text replaces the original.";
}

Note that after is the pseudo element in use here. We use the visibility modifier once again to show the new text. The content attribute contains the new text.
Example:

<html>

<head>

    <style>

        .toBeReplaced {

            visibility: hidden;

            position: relative;

        }

        .toBeReplaced:after {

            visibility: visible;

            position: absolute;

            top: 0;

            left: 0;

            content: "This text replaces the original.";

        }

    </style>

</head>

<body>

    <p class="toBeReplaced">Old Text</p>

</body>

</html>

Output:

This text replaces the original.

Method 2: Using Pseudo Elements and Visibility Modifier with <span> tag 
In this method, we need a little bit more markup but we no longer need to specify any absolute positioning for our new text. We wrap the text using <span> tags.

<p class="toBeReplaced"><span>Old Text</span></p>

In this method, we use a child element to wrap the text, that is, the text is now inside <p> and <span> tags. So we can use the display: none CSS attribute to hide the text in the <span> element. Then we can simply replace the text as we did in the previous method, without specifying any positioning.

.toBeReplaced span {
    display: none;
}

.toBeReplaced:after {
    content: "This text replaces the original.";
}

Example:

<html>

<head>

    <style>

        .toBeReplaced span {

            display: none;

        }

        .toBeReplaced:after {

            content: "This text replaces the original.";

        }

    </style>

</head>

<body>

    <p class="toBeReplaced"><span>Old Text</span></p>

</body>

</html>

Output:

This text replaces the original.

CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.

Today We will learn How to Replace a content with CSS

Replacing a  content with CSS is not something I utilize frequently, but rather there are some particular situations where it proves to be useful. In the event that you can change message on the server-side, I generally suggest that first. CSS content substitution ought to be a final resort, as that is not what CSS is expected for.

In case you’re working inside the constraints of a CMS, or you don’t be able to change your markup, CSS content Replacing  may be your exclusive choice.

There are a couple approaches to handle it. We should stroll through the alternatives, and clarify how they work, and why different strategies come up short.

N.B.: In the majority of the accompanying illustrations, you could utilize either pseudo-component, :before or :after

Text Replacement with Pseudo-elements & CSS Visibility

A decent contention can be made this is the best strategy. It requires the littlest measure of markup, and functions admirably for the individuals who have practically no power over their HTML markup. Here’s some HTML:

<div class="replaced-content">Original Content</div>

You want to replace “Original Text” with various content. Here’s how you can replace that text using only CSS.

.replaced-content {
visibility: hidden;
position: relative;
}

.replaced-content:after {
visibility: visible;
position: absolute;
top: 0;
left: 0;
content: "This text replaces the original.";
}

Giving visibility a value of hiddenhides a component, however leaves space where it would have been. As it were, it doesn’t change the design of the page. (This is different from display: none;, which we’ll cover below.) This is the reason we have to utilize positioning the pseudo-element.Without absolutely positioning the pseudo-element, the new content would show up after the spot where the first content should be. By using absolute positioning, we can place the new text in exactly the same spot as the original text was supposed to appear.

Text Replacement with Pseudo-elements & CSS Display

This method requires a little extra markup in your HTML, but uses less CSS. Like the example above, it also utilizes a CSS pseudo-element to insert content onto the page. The HTML (note the extra tag that was not in our example above):

With Pseudo-elements & CSS Display This technique requires somewhat additional markup in your HTML, however utilizes less CSS. Like the case above, it additionally uses a CSS pseudo-component to embed content onto the page. The HTML (take note of the additional tag that was not in our case above):

<div class="replaced-content">Original Content</div>

Utilizing the display property, you can hide the content inside the tag, and then attach a pseudo-element with your new content to the

tag. You do not need to use absolute positioning here because display: none;  completely removes the element from the page, and it does affect the layout. It’s as if the text inside the element never existed.
Here’s the CSS:

.replaced span {
	display: none;
}

.replaced:after {
	content: "This text replaces the original.";
}

display: none; will not work without the extra markup

If you didn’t have that extra element (in this case, the tag) inside of your

tag, you cannot use display: none;. Any time you have a parent element with display: none;, all of its child elements, as well as its pseudo-elements, will not be displayed. Even if you set the pseudo-element to display: block;

So, if this is your HTML:

<div class=”replaced-content”>Original Content</div>

Then this CSS will not work:

.replaced { display: none; } .replaced:after { display: block; content: "This text replaces the original."; }

Using Special Characters & Symbols in Replaced Text

You might want to replace text with special characters or symbols, like an ampersand, tilde, emdash or non-breaking space. To do so, you must using the proper character encoding for that symbol. You cannot just place the symbol inside your content: “”;  declaration, nor can you use the HTML code (e.g. &amp;  & or &mdash; ).

This entity conversion chart will convert your special character, and give you the appropriate code to use with the CSS content  property.

If you wanted to insert this: 29.9 = ~30

It would look like this:

content: “29.9 03D 020 07E 30”;

  • 03D is the code for an equals sign (=)
  • 020 is the code for a non-breaking space ( &nbsp;  )
  • 07E is the code for a tilde (~)

Need to include spaces within each special character code, otherwise the codes run together & CSS doesn’t know where the beginning & end of each code is located.

На этом уроке мы познакомимся с основными приёмами для работы с текстом с помощью средств CSS.

Задавать стили CSS к тексту можно на уровне элемента body (для всей веб-страницы), элемента p (для абзаца), элемента span (для выделенного фрагмента текста) или любого другого элемента HTML.

Основные свойства CSS для работы с текстом

1. Свойство font-size

Свойство font-size изменяет размер шрифта. Оно задаётся с помощью значения и единицы измерения (em, px, pt, %). Единицы измерения em и % являются относительными и зависят от размера шрифта установленного в документе. Единицы измерения px и pt являются абсолютными и их размер зависит от разрешения экрана. Также у данного свойства есть предопределенные значения small и larger, которые соответственно уменьшают или увеличивают текст по отношению к базовому.

<p style="font-size:1em;">Lorem ipsum dolor sit amet</p>
<p style="font-size:120%;">Lorem ipsum dolor sit amet</p>
<p style="font-size:16px;">Lorem ipsum dolor sit amet</p>
<p style="font-size:14pt;">Lorem ipsum dolor sit amet</p>  
<p style="font-size:larger;">Lorem ipsum dolor sit amet</p>
<p style="font-size:small;">Lorem ipsum dolor sit amet</p>

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

2. Свойство font-weight

Свойство font-weight изменяет жирность шрифта. Свойство font-weight имеет 2 часто используемых значения: normal (обычное) и bold (жирное). Остальные значения используются очень редко, перечислим их: числовые от 100 до 900 с шагом 100 (100 – самое тонкое начертание, 900 – самое жирное начертание), bolder и lighter.

<p style="font-weight:normal;">Lorem ipsum dolor sit amet</p>
<p style="font-weight:bold;">Lorem ipsum dolor sit amet</p>
<p style="font-weight:200;">Lorem ipsum dolor sit amet</p>
<p style="font-weight:900;">Lorem ipsum dolor sit amet</p>  
<p style="font-weight:lighter;">Lorem ipsum dolor sit amet</p>
<p style="font-weight:bolder;">Lorem ipsum dolor sit amet</p>

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

3. Свойство font-style

Свойство font-style устанавливает тексту курсивное начертание. Оно принимает следующие значения: normal (обычное начертание шрифта), italic (курсивное начертание).

<p style="font-style:normal;">Lorem ipsum dolor sit amet</p>
<p style="font-style:italic;">Lorem ipsum dolor sit amet</p>

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

4. Свойство font-family

Свойство font-family изменяет шрифт или список шрифтов с помощью которых отображается текст. В качестве значений свойство font-family принимает названия шрифтов (например: font-family: «Tahoma», «Arial») или предопределенные названия группы шрифтов (serif, sans-serif, monospace, fantasy, cursive).

<p style="font-family:'Times New Roman','Arial';">Lorem ipsum dolor sit amet</p>
<p style="font-family:serif;">Lorem ipsum dolor sit amet</p>
<p style="font-family:sans-serif;">Lorem ipsum dolor sit amet</p>
<p style="font-family:monospace;">Lorem ipsum dolor sit amet</p>
<p style="font-family:fantasy;">Lorem ipsum dolor sit amet</p>
<p style="font-family:cursive;">Lorem ipsum dolor sit amet</p>

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

5. Свойство color

Свойство color изменяет цвет шрифта. Установить цвет можно несколькими способами: #ff0000 (шестнадцатеричное значение цвета), orange (зарезервированное название цвета), rgb(120,17,90) (RGB значение).

<p style="color:#aa00aa;">Lorem ipsum dolor sit amet</p>
<p style="color:pink;">Lorem ipsum dolor sit amet</p>
<p style="color:rgb(17,17,17)">Lorem ipsum dolor sit amet</p>

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

6. Свойство background-color

Свойство background-color можно использовать для выделения текста цветом, т.е. текст делается похожим на текст выделенный маркером. Установить цвет можно такими же способами, как и для свойства color.

<p>Lorem ipsum <span style="background-color:yellow;">dolor sit</span> amet</p>
<p style="color:orange;">Lorem ipsum dolor <span style="background-color:green;">sit amet</span></p>
<p><span style="background-color:gray;">Lorem</span> ipsum dolor sit amet</p>

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

6. Свойство text-decoration

Свойство text-decoration можно использовать для декоративного оформления текста. В качестве значений свойства text-decoration можно использовать следующие: none (без декоративного оформления), underline (подчёркивание), overline (линия над текстом), line-through (зачёркивание), blink (эффект мигания).

<p style="text-decoration:none;">Lorem ipsum dolor sit amet</p>
<p style="text-decoration:underline;">Lorem ipsum dolor sit amet</p>
<p style="text-decoration:overline;">Lorem ipsum dolor sit amet</p>
<p style="text-decoration:line-through;">Lorem ipsum dolor sit amet</p>
<p style="text-decoration:underline line-through;">Lorem ipsum dolor sit amet</p>

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

Подчёркивание также можно создать с помощью свойства CSS border.

<p>Lorem ipsum <span style="color:red; text-decoration: none;
border-bottom: 1px dashed red;">dolor sit</span> amet</p>
<p><span style="color:blue; text-decoration: none;
border-bottom: 1px dashed blue;">Lorem </span>ipsum dolor sit amet</p>

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

7. Свойство text-transform

Свойство text-transform управляет регистром символов. В качестве значений свойства text-transform можно использовать следующие: none (по умолчанию), lowercase (переводит все символы в строчные), uppercase (переводит все символы в прописные), capitalize (каждое слово начинается с прописного символа).

<p style="text-transform:none;">Lorem ipsum dolor sit amet</p>
<p style="text-transform:lowercase;">Lorem ipsum dolor sit amet</p>
<p style="text-transform:uppercase;">Lorem ipsum dolor sit amet</p>
<p style="text-transform:capitalize;">Lorem ipsum dolor sit amet</p>

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

8. Свойство white-space

При обработке текста браузер не отображает больше одного пробела между словами, а также игнорирует переносы строк, которые вы выполнили в HTML коде. При помощи свойства white-space вы можете настроить поведение браузера с помощью следующих значений: normal (по умолчанию), nowrap (не переносит текст, пока не встретит тег br), pre (отображает текст как в коде на HTML), pre-wrap (отображает все пробелы между словами и переносит текст, если он не помещается в контейнер).

<p style="white-space:normal;">Lorem    ipsum 

dolor sit amet</p>
<hr>
<p style="white-space:pre;">Lorem    ipsum 

dolor sit amet</p>

Lorem ipsum

dolor sit amet


Lorem ipsum

dolor sit amet

9. Свойство text-align

Свойство text-align предназначено для выравнивания текста в горизонтальном направлении. Значения свойства text-align указывают, что текст будет выровнен: left (по левому краю), center (по центру), right (по правому краю), justify (по ширине, т.е. одновременно по левому и правому краям).

<p style="text-align:left;">...</p>
<hr>
<p style="text-align:center;">...</p>
<hr>
<p style="text-align:right;">...</p>
<hr>
<p style="text-align:justify;">...</p>

Lorem ipsum dolor sit amet. Impedit, quo voluptas assumenda est, qui minus id quod. Quas molestias excepturi sint, obcaecati cupiditate non numquam eius. Perspiciatis, unde omnis iste natus error sit voluptatem. Et harum quidem rerum facilis est laborum et molestiae consequatur. Minus id, quod maxime placeat, facere possimus. Quo minus id, quod maxime placeat facere. Et molestiae consequatur, vel eum iure reprehenderit, qui dolorem ipsum, quia consequuntur.


Lorem ipsum dolor sit amet. Impedit, quo voluptas assumenda est, qui minus id quod. Quas molestias excepturi sint, obcaecati cupiditate non numquam eius. Perspiciatis, unde omnis iste natus error sit voluptatem. Et harum quidem rerum facilis est laborum et molestiae consequatur. Minus id, quod maxime placeat, facere possimus. Quo minus id, quod maxime placeat facere. Et molestiae consequatur, vel eum iure reprehenderit, qui dolorem ipsum, quia consequuntur.


Lorem ipsum dolor sit amet. Impedit, quo voluptas assumenda est, qui minus id quod. Quas molestias excepturi sint, obcaecati cupiditate non numquam eius. Perspiciatis, unde omnis iste natus error sit voluptatem. Et harum quidem rerum facilis est laborum et molestiae consequatur. Minus id, quod maxime placeat, facere possimus. Quo minus id, quod maxime placeat facere. Et molestiae consequatur, vel eum iure reprehenderit, qui dolorem ipsum, quia consequuntur.


Lorem ipsum dolor sit amet. Impedit, quo voluptas assumenda est, qui minus id quod. Quas molestias excepturi sint, obcaecati cupiditate non numquam eius. Perspiciatis, unde omnis iste natus error sit voluptatem. Et harum quidem rerum facilis est laborum et molestiae consequatur. Minus id, quod maxime placeat, facere possimus. Quo minus id, quod maxime placeat facere. Et molestiae consequatur, vel eum iure reprehenderit, qui dolorem ipsum, quia consequuntur.

10. Свойство vertical-align

Свойство vertical-align может использоваться для строчных элементов (в том числе для элементов со свойством display:inline-block), ячеек таблицы, и предназначено для выравнивания текста по вертикали. Значения свойства vertical-align указывают, что текст будет выровнен: top (по верхнему краю строки), middle (по середине), bottom (по нижнему краю строки), baseline (значение по умолчанию, выравнивание по базовой линии), sub (текст отображается в виде нижнего индекса, как подстрочный), super (текст отображается в виде верхнего индекса, как надстрочный).

<p style="font-size:2em; background:paleturquoise;">Lorem ipsum dolor <small style="font-size:0.5em; vertical-align:top;">sit amet</small>.</p>
<hr>
<p style="font-size:2em; background:paleturquoise;">Lorem ipsum dolor <small style="font-size:0.5em; vertical-align:middle;">sit amet</small>.</p>
<hr>
<p style="font-size:2em; background:paleturquoise;">Lorem ipsum dolor <small style="font-size:0.5em; vertical-align:bottom;">sit amet</small>.</p>
<hr>
<p style="font-size:2em; background:paleturquoise;">Lorem ipsum dolor <small style="font-size:0.5em; vertical-align:baseline;">sit amet</small>.</p>
<hr>
<p style="font-size:2em; background:paleturquoise;">Lorem <span style="vertical-align:sub">ipsum</span> dolor <span style="vertical-align:super">sit amet</span>.</p>

Lorem ipsum dolor sit amet.


Lorem ipsum dolor sit amet.


Lorem ipsum dolor sit amet.


Lorem ipsum dolor sit amet.


Lorem ipsum dolor sit amet.

11. Свойство line-height

Свойство line-height предназначено для задания высоты строки, которая влияет на расстояние между строчками текста. В качестве значений свойства line-height можно использовать следующие: число (множитель по отношению к значению высоты строки по умолчанию), проценты (например: 120% от высоты строки по умолчанию), px (например: 16px), em (например: 3em), зарезервированное слово normal (автоматический расчёт высоты).

<p>...</p>
<hr>
<p style="line-height:200%;">...</p>
<hr>
<p style="line-height:3;">...</p>
<hr>
<p style="line-height:normal;">...</p>
<hr>
<p style="line-height:24px;">...</p>

Lorem ipsum dolor sit amet. Eos et quas molestias excepturi sint. Tempora incidunt, ut aliquid. Quibusdam et molestiae non provident, similique sunt in culpa, qui in. Eligendi optio, cumque nihil molestiae consequatur, vel eum fugiat. Alias consequatur aut fugit. Ducimus, qui blanditiis praesentium voluptatum deleniti atque corrupti.


Lorem ipsum dolor sit amet. Eos et quas molestias excepturi sint. Tempora incidunt, ut aliquid. Quibusdam et molestiae non provident, similique sunt in culpa, qui in. Eligendi optio, cumque nihil molestiae consequatur, vel eum fugiat. Alias consequatur aut fugit. Ducimus, qui blanditiis praesentium voluptatum deleniti atque corrupti.


Lorem ipsum dolor sit amet. Eos et quas molestias excepturi sint. Tempora incidunt, ut aliquid. Quibusdam et molestiae non provident, similique sunt in culpa, qui in. Eligendi optio, cumque nihil molestiae consequatur, vel eum fugiat. Alias consequatur aut fugit. Ducimus, qui blanditiis praesentium voluptatum deleniti atque corrupti.


Lorem ipsum dolor sit amet. Eos et quas molestias excepturi sint. Tempora incidunt, ut aliquid. Quibusdam et molestiae non provident, similique sunt in culpa, qui in. Eligendi optio, cumque nihil molestiae consequatur, vel eum fugiat. Alias consequatur aut fugit. Ducimus, qui blanditiis praesentium voluptatum deleniti atque corrupti.


Lorem ipsum dolor sit amet. Eos et quas molestias excepturi sint. Tempora incidunt, ut aliquid. Quibusdam et molestiae non provident, similique sunt in culpa, qui in. Eligendi optio, cumque nihil molestiae consequatur, vel eum fugiat. Alias consequatur aut fugit. Ducimus, qui blanditiis praesentium voluptatum deleniti atque corrupti.

Основы стилизирования текста и шрифта

  • Обзор: Styling text
  • Далее

В данной статье мы начнём путь к овладению стилизацией текста при помощи CSS. Мы подробно изучим основы стилизации текста и шрифта, такие как толщина, начертание, семейство, стенография, выравнивание текста и другие эффекты, а также рассмотрим междустрочный и межбуквенный интервалы.

Необходимые знания: Базовые компьютерные знания, Основы HTML (раздел Введение в HTML), основы CSS (раздел Введение в CSS).
Задача: Изучить основные свойства и техники, необходимые для стилизации текста на веб-страницах.

Что участвует в стилизации текста в CSS?

Как вы уже проверили в своей работе с HTML и CSS, текст внутри элемента выкладывается в поле содержимого элемента. Он начинается в левом верхнем углу области содержимого (или в правом верхнем углу, в случае содержимого языка RTL) и течёт к концу строки. Как только он достигает конца, он переходит к следующей строке и продолжает, затем к следующей строке, пока все содержимое не будет помещено в коробку. Текстовое содержимое эффективно ведёт себя как ряд встроенных элементов, размещённых на соседних строках и не создающих разрывы строк до тех пор, пока не будет достигнут конец строки, или если вы не принудите разрыв строки вручную с помощью элемента <br>.

Примечание: если приведённый выше абзац оставляет вас в замешательстве, то не имеет значения — вернитесь и просмотрите нашу статью о модели коробки, чтобы освежить теорию модели коробки, прежде чем продолжить.

Свойства CSS, используемые для стилизации текста, обычно делятся на две категории, которые мы рассмотрим отдельно в этой статье:

  • Font styles: Свойства, влияющие на шрифт, применяемый к тексту, влияющие на то, какой шрифт применяется, насколько он велик, является ли он полужирным, курсивным и т. д.
  • Text layout styles: Свойства, влияющие на интервал и другие особенности компоновки текста, позволяющие манипулировать, например, пространством между строками и буквами, а также тем, как текст выравнивается в поле содержимого.

Примечание: имейте в виду, что текст внутри элемента все затронуты как одна единая сущность. Вы не можете выбирать и стилизовать подразделы текста, если вы не обернёте их в соответствующий элемент (например, <span> или <strong>), или использовать текстовый псевдоэлемент, такой как ::first-letter (выделяет первую букву текста элемента),:: first-line (выделяет первую строку текста элемента) или ::selection (выделяет текст, выделенный в данный момент курсором.)

Шрифты

Давайте сразу перейдём к рассмотрению свойств для стилизации шрифтов. В этом примере мы применим некоторые различные свойства CSS к одному и тому же образцу HTML, который выглядит следующим образом:

<h1>Tommy the cat</h1>

<p>Well I remember it as though it were a meal ago...</p>

<p>Said Tommy the Cat as he reeled back to clear whatever foreign matter
 may have nestled its way into his mighty throat. Many a fat alley rat
had met its demise while staring point blank down the cavernous barrel of
 this awesome prowling machine. Truly a wonder of nature this urban
predator — Tommy the cat had many a story to tell. But it was a rare
occasion such as this that he did.</p>

You can find the finished example on GitHub (see also the source code.)

Color

The color (en-US) property sets the color of the foreground content of the selected elements (which is usually the text, but can also include a couple of other things, such as an underline or overline placed on text using the text-decoration (en-US) property).

color can accept any CSS color unit, for example:

This will cause the paragraphs to become red, rather than the standard browser default black, like so:

<h1>Tommy the cat</h1>

<p>Well I remember it as though it were a meal ago...</p>

<p>Said Tommy the Cat as he reeled back to clear whatever foreign matter
 may have nestled its way into his mighty throat. Many a fat alley rat
had met its demise while staring point blank down the cavernous barrel of
 this awesome prowling machine. Truly a wonder of nature this urban
predator — Tommy the cat had many a story to tell. But it was a rare
occasion such as this that he did.</p>

Font families

To set a different font on your text, you use the font-family property — this allows you to specify a font (or list of fonts) for the browser to apply to the selected elements. The browser will only apply a font if it is available on the machine the website is being accessed on; if not, it will just use a browser default font. A simple example looks like so:

p {
  font-family: arial;
}

This would make all paragraphs on a page adopt the arial font, which is found on any computer.

Web safe fonts

Speaking of font availability, there are only a certain number of fonts that are generally available across all systems and can therefore be used without much worry. These are the so-called web safe fonts.

Most of the time, as web developers we want to have more specific control over the fonts used to display our text content. The problem is to find a way to know which font is available on the computer used to see our web pages. There is no way to know this in every case, but the web safe fonts are known to be available on nearly all instances of the most used operating systems (Windows, macOS, the most common Linux distributions, Android, and iOS).

The list of actual web safe fonts will change as operating systems evolve, but it’s reasonable to consider the following fonts web safe, at least for now (many of them have been popularized thanks to the Microsoft Core fonts for the Web initiative in the late 90s and early 2000s):

Name Generic type Notes
Arial sans-serif It’s often considered best practice to also add Helvetica as a preferred alternative to Arial as, although their font faces are almost identical, Helvetica is considered to have a nicer shape, even if Arial is more broadly available.
Courier New monospace Some OSes have an alternative (possibly older) version of the Courier New font called Courier. It’s considered best practice to use both with Courier New as the preferred alternative.
Georgia serif
Times New Roman serif Some OSes have an alternative (possibly older) version of the Times New Roman font called Times. It’s considered best practice to use both with Times New Roman as the preferred alternative.
Trebuchet MS sans-serif You should be careful with using this font — it isn’t widely available on mobile OSes.
Verdana sans-serif

Примечание: Among various resources, the cssfontstack.com website maintains a list of web safe fonts available on Windows and macOS operating systems, which can help you make your decision about what you consider safe for your usage.

Примечание: There is a way to download a custom font along with a webpage, to allow you to customize your font usage in any way you want: web fonts. This is a little bit more complex, and we will be discussing this in a separate article later on in the module.

Default fonts

CSS defines five generic names for fonts: serif, sans-serif, monospace, cursive and fantasy. Those are very generic and the exact font face used when using those generic names is up to each browser and can vary for each operating system they are running on. It represents a worst case scenario where the browser will try to do its best to provide at least a font that looks appropriate. serif, sans-serif and monospace are quite predictable and should provide something reasonable. On the other hand, cursive and fantasy are less predictable and we recommend using them very carefully, testing as you go.

The five names are defined as follows:

Term Definition Example
serif Fonts that have serifs (the flourishes and other small details you see at the ends of the strokes in some typefaces) My big red elephant
sans-serif Fonts that don’t have serifs. My big red elephant
monospace Fonts where every character has the same width, typically used in code listings. My big red elephant
cursive Fonts that are intended to emulate handwriting, with flowing, connected strokes. My big red elephant
fantasy Fonts that are intended to be decorative. My big red elephant

Font stacks

Since you can’t guarantee the availability of the fonts you want to use on your webpages (even a web font could fail for some reason), you can supply a font stack so that the browser has multiple fonts it can choose from. This simply involves a font-family value consisting of multiple font names separated by commas, e.g.

p {
  font-family: "Trebuchet MS", Verdana, sans-serif;
}

In such a case, the browser starts at the beginning of the list and looks to see if that font is available on the machine. If it is, it applies that font to the selected elements. If not, it moves on to the next font, and so on.

It is a good idea to provide a suitable generic font name at the end of the stack so that if none of the listed fonts are available, the browser can at least provide something approximately suitable. To emphasise this point, paragraphs are given the browser’s default serif font if no other option is available — which is usually Times New Roman — this is no good for a sans-serif font!

Примечание: Font names that have more than one word — like Trebuchet MS — need to be surrounded by quotes, for example "Trebuchet MS".

A font-family example

Let’s add to our previous example, giving the paragraphs a sans-serif font:

p {
  color: red;
  font-family: Helvetica, Arial, sans-serif;
}

This gives us the following result:

<h1>Tommy the cat</h1>

<p>Well I remember it as though it were a meal ago...</p>

<p>Said Tommy the Cat as he reeled back to clear whatever foreign matter
 may have nestled its way into his mighty throat. Many a fat alley rat
had met its demise while staring point blank down the cavernous barrel of
 this awesome prowling machine. Truly a wonder of nature this urban
predator — Tommy the cat had many a story to tell. But it was a rare
occasion such as this that he did.</p>

Font size

In our previous module’s CSS values and units article, we reviewed length and size units. Font size (set with the font-size property) can take values measured in most of these units (and others, such as percentages), however the most common units you’ll use to size text are:

  • px (pixels): The number of pixels high you want the text to be. This is an absolute unit — it results in the same final computed value for the font on the page in pretty much any situation.
  • ems: 1 em is equal to the font size set on the parent element of the current element we are styling (more specifically, the width of a capital letter M contained inside the parent element.) This can become tricky to work out if you have a lot of nested elements with different font sizes set, but it is doable, as you’ll see below. Why bother? It is quite natural once you get used to it, and you can use em to size everything, not just text. You can have an entire website sized using em, which makes maintenance easy.
  • rems: These work just like em, except that 1 rem is equal to the font size set on the root element of the document (i.e. <html>), not the parent element. This makes doing the maths to work out your font sizes much easier, although if you want to support really old browsers, you might struggle — rem is not supported in Internet Explorer 8 and below.

The font-size of an element is inherited from that element’s parent element. This all starts with the root element of the entire document — <html> — the font-size of which is set to 16px as standard across browsers. Any paragraph (or another element that doesn’t have a different size set by the browser) inside the root element will have a final size of 16 px. Other elements may have different default sizes, for example an <h1> (en-US) element has a size of 2 em set by default, so it will have a final size of 32 px.

Things become more tricky when you start altering the font size of nested elements. For example, if you had an <article> element in your page, and set its font-size to 1.5 em (which would compute to 24 px final size), and then wanted the paragraphs inside the <article> elements to have a computed font size of 20 px, what em value would you use?

<!-- document base font-size is 16px -->
<article> <!-- If my font-size is 1.5em -->
  <p>My paragraph</p> <!-- How do I compute to 20px font-size? -->
</article>

You would need to set its em value to 20/24, or 0.83333333 em. The maths can be complicated, so you need to be careful about how you style things. It is best to use rem where you can, to keep things simple, and avoid setting the font-size of container elements where possible.

A simple sizing example

When sizing your text, it is usually a good idea to set the base font-size of the document to 10 px, so that then the maths is a lot easier to work out — required (r)em values are then the pixel font size divided by 10, not 16. After doing that, you can easily size the different types of text in your document to what you want. It is a good idea to list all your font-size rulesets in a designated area in your stylesheet, so they are easy to find.

Our new result is like so:

<h1>Tommy the cat</h1>

<p>Well I remember it as though it were a meal ago...</p>

<p>Said Tommy the Cat as he reeled back to clear whatever foreign matter
 may have nestled its way into his mighty throat. Many a fat alley rat
had met its demise while staring point blank down the cavernous barrel of
 this awesome prowling machine. Truly a wonder of nature this urban
predator — Tommy the cat had many a story to tell. But it was a rare
occasion such as this that he did.</p>
html {
  font-size: 10px;
}

h1 {
  font-size: 5rem;
}

p {
  font-size: 1.5rem;
  color: red;
  font-family: Helvetica, Arial, sans-serif;
}

Font style, font weight, text transform, and text decoration

CSS provides four common properties to alter the visual weight/emphasis of text:

  • font-style: Used to turn italic text on and off. Possible values are as follows (you’ll rarely use this, unless you want to turn some italic styling off for some reason):
    • normal: Sets the text to the normal font (turns existing italics off.)
    • italic: Sets the text to use the italic version of the font if available; if not available, it will simulate italics with oblique instead.
    • oblique: Sets the text to use a simulated version of an italic font, created by slanting the normal version.
  • font-weight: Sets how bold the text is. This has many values available in case you have many font variants available (such as -light, -normal, -bold, -extrabold, -black, etc.), but realistically you’ll rarely use any of them except for normal and bold:
    • normal, bold: Normal and bold font weight
    • lighter, bolder: Sets the current element’s boldness to be one step lighter or heavier than its parent element’s boldness.
    • 100900: Numeric boldness values that provide finer grained control than the above keywords, if needed.
  • text-transform (en-US): Allows you to set your font to be transformed. Values include:
    • none: Prevents any transformation.
    • uppercase: Transforms all text to capitals.
    • lowercase: Transforms all text to lower case.
    • capitalize: Transforms all words to have the first letter capitalized.
    • full-width: Transforms all glyphs to be written inside a fixed-width square, similar to a monospace font, allowing aligning of e.g. Latin characters along with Asian language glyphs (like Chinese, Japanese, Korean).
  • text-decoration (en-US): Sets/unsets text decorations on fonts (you’ll mainly use this to unset the default underline on links when styling them.) Available values are:
    • none: Unsets any text decorations already present.
    • underline: Underlines the text.
    • overline: Gives the text an overline.
    • line-through: Puts a strikethrough over the text.

    You should note that text-decoration (en-US) can accept multiple values at once, if you want to add multiple decorations simultaneously, for example text-decoration: underline overline. Also note that text-decoration (en-US) is a shorthand property for text-decoration-line (en-US), text-decoration-style (en-US), and text-decoration-color (en-US). You can use combinations of these property values to create interesting effects, for example text-decoration: line-through red wavy.

Let’s look at adding a couple of these properties to our example:

Our new result is like so:

<h1>Tommy the cat</h1>

<p>Well I remember it as though it were a meal ago...</p>

<p>Said Tommy the Cat as he reeled back to clear whatever foreign matter
 may have nestled its way into his mighty throat. Many a fat alley rat
had met its demise while staring point blank down the cavernous barrel of
 this awesome prowling machine. Truly a wonder of nature this urban
predator — Tommy the cat had many a story to tell. But it was a rare
occasion such as this that he did.</p>
html {
  font-size: 10px;
}

h1 {
  font-size: 5rem;
  text-transform: capitalize;
}

h1 + p {
  font-weight: bold;
}

p {
  font-size: 1.5rem;
  color: red;
  font-family: Helvetica, Arial, sans-serif;
}

Text drop shadows

You can apply drop shadows to your text using the text-shadow property. This takes up to four values, as shown in the example below:

text-shadow: 4px 4px 5px red;

The four properties are as follows:

  1. The horizontal offset of the shadow from the original text — this can take most available CSS length and size units, but you’ll most commonly use px; positive values move the shadow right, and negative values left. This value has to be included.
  2. The vertical offset of the shadow from the original text; behaves basically just like the horizontal offset, except that it moves the shadow up/down, not left/right. This value has to be included.
  3. The blur radius — a higher value means the shadow is dispersed more widely. If this value is not included, it defaults to 0, which means no blur. This can take most available CSS length and size units.
  4. The base color of the shadow, which can take any CSS color unit. If not included, it defaults to black.

Multiple shadows

You can apply multiple shadows to the same text by including multiple shadow values separated by commas, for example:

text-shadow: 1px 1px 1px red,
             2px 2px 1px red;

If we applied this to the <h1> (en-US) element in our Tommy the cat example, we’d end up with this:

<h1>Tommy the cat</h1>

<p>Well I remember it as though it were a meal ago...</p>

<p>Said Tommy the Cat as he reeled back to clear whatever foreign matter
 may have nestled its way into his mighty throat. Many a fat alley rat
had met its demise while staring point blank down the cavernous barrel of
 this awesome prowling machine. Truly a wonder of nature this urban
predator — Tommy the cat had many a story to tell. But it was a rare
occasion such as this that he did.</p>
html {
  font-size: 10px;
}

h1 {
  font-size: 5rem;
  text-transform: capitalize;
  text-shadow: 1px 1px 1px red,
               2px 2px 1px red;
}

h1 + p {
  font-weight: bold;
}

p {
  font-size: 1.5rem;
  color: red;
  font-family: Helvetica, Arial, sans-serif;
}

Text layout

With basic font properties out the way, let’s now have a look at properties we can use to affect text layout.

Text alignment

The text-align property is used to control how text is aligned within its containing content box. The available values are as follows, and work in pretty much the same way as they do in a regular word processor application:

  • left: Left-justifies the text.
  • right: Right-justifies the text.
  • center: Centers the text.
  • justify: Makes the text spread out, varying the gaps in between the words so that all lines of text are the same width. You need to use this carefully — it can look terrible, especially when applied to a paragraph with lots of long words in it. If you are going to use this, you should also think about using something else along with it, such as hyphens, to break some of the longer words across lines.

If we applied text-align: center; to the <h1> (en-US) in our example, we’d end up with this:

<h1>Tommy the cat</h1>

<p>Well I remember it as though it were a meal ago...</p>

<p>Said Tommy the Cat as he reeled back to clear whatever foreign matter
 may have nestled its way into his mighty throat. Many a fat alley rat
had met its demise while staring point blank down the cavernous barrel of
 this awesome prowling machine. Truly a wonder of nature this urban
predator — Tommy the cat had many a story to tell. But it was a rare
occasion such as this that he did.</p>
html {
  font-size: 10px;
}

h1 {
  font-size: 5rem;
  text-transform: capitalize;
  text-shadow: 1px 1px 1px red,
               2px 2px 1px red;
  text-align: center;
}

h1 + p {
  font-weight: bold;
}

p {
  font-size: 1.5rem;
  color: red;
  font-family: Helvetica, Arial, sans-serif;
}

Line height

The line-height property sets the height of each line of text — this can take most length and size units, but can also take a unitless value, which acts as a multiplier and is generally considered the best option — the font-size is multiplied to get the line-height. Body text generally looks nicer and is easier to read when the lines are spaced apart; the recommended line height is around 1.5 – 2 (double spaced.) So to set our lines of text to 1.6 times the height of the font, you’d use this:

Applying this to the <p> elements in our example would give us this result:

<h1>Tommy the cat</h1>

<p>Well I remember it as though it were a meal ago...</p>

<p>Said Tommy the Cat as he reeled back to clear whatever foreign matter
 may have nestled its way into his mighty throat. Many a fat alley rat
had met its demise while staring point blank down the cavernous barrel of
 this awesome prowling machine. Truly a wonder of nature this urban
predator — Tommy the cat had many a story to tell. But it was a rare
occasion such as this that he did.</p>
html {
  font-size: 10px;
}

h1 {
  font-size: 5rem;
  text-transform: capitalize;
  text-shadow: 1px 1px 1px red,
               2px 2px 1px red;
  text-align: center;
}

h1 + p {
  font-weight: bold;
}

p {
  font-size: 1.5rem;
  color: red;
  font-family: Helvetica, Arial, sans-serif;
  line-height: 1.6;
}

Letter and word spacing

The letter-spacing and word-spacing properties allow you to set the spacing between letters and words in your text. You won’t use these very often, but might find a use for them to get a certain look, or to improve the legibility of a particularly dense font. They can take most length and size units.

So as an example, we could apply some word- and letter-spacing to the first line of each <p> element in our example:

p::first-line {
  letter-spacing: 4px;
  word-spacing: 4px;
}

Let’s add some to our example, like so:

<h1>Tommy the cat</h1>

<p>Well I remember it as though it were a meal ago...</p>

<p>Said Tommy the Cat as he reeled back to clear whatever foreign matter
 may have nestled its way into his mighty throat. Many a fat alley rat
had met its demise while staring point blank down the cavernous barrel of
 this awesome prowling machine. Truly a wonder of nature this urban
predator — Tommy the cat had many a story to tell. But it was a rare
occasion such as this that he did.</p>
html {
  font-size: 10px;
}

h1 {
  font-size: 5rem;
  text-transform: capitalize;
  text-shadow: 1px 1px 1px red,
               2px 2px 1px red;
  text-align: center;
  letter-spacing: 2px;
}

h1 + p {
  font-weight: bold;
}

p::first-line {
  letter-spacing: 4px;
  word-spacing: 4px;
}

p {
  font-size: 1.5rem;
  color: red;
  font-family: Helvetica, Arial, sans-serif;
  line-height: 1.6;
  letter-spacing: 1px;
}

Other properties worth looking at

The above properties give you an idea of how to start styling text on a webpage, but there are many more properties you could use. We just wanted to cover the most important ones here. Once you’ve become used to using the above, you should also explore the following:

Font styles:

  • font-variant (en-US): Switch between small caps and normal font alternatives.
  • font-kerning (en-US): Switch font kerning options on and off.
  • font-feature-settings (en-US): Switch various OpenType font features on and off.
  • font-variant-alternates (en-US): Control the use of alternate glyphs for a given font-face.
  • font-variant-caps (en-US): Control the use of alternate capital glyphs.
  • font-variant-east-asian (en-US): Control the usage of alternate glyphs for East Asian scripts, like Japanese and Chinese.
  • font-variant-ligatures: Control which ligatures and contextual forms are used in text.
  • font-variant-numeric: Control the usage of alternate glyphs for numbers, fractions, and ordinal markers.
  • font-variant-position (en-US): Control the usage of alternate glyphs of smaller sizes positioned as superscript or subscript.
  • font-size-adjust (en-US): Adjust the visual size of the font independently of its actual font size.
  • font-stretch (en-US): Switch between possible alternative stretched versions of a given font.
  • text-underline-position (en-US): Specify the position of underlines set using the text-decoration-line property underline value.
  • text-rendering (en-US): Try to perform some text rendering optimization.

Text layout styles:

  • text-indent: Specify how much horizontal space should be left before the beginning of the first line of the text content.
  • text-overflow (en-US): Define how overflowed content that is not displayed is signaled to users.
  • white-space: Define how whitespace and associated line breaks inside the element are handled.
  • word-break: Specify whether to break lines within words.
  • direction: Define the text direction (This depends on the language and usually it’s better to let HTML handle that part as it is tied to the text content.)
  • hyphens: Switch on and off hyphenation for supported languages.
  • line-break: Relax or strengthen line breaking for Asian languages.
  • text-align-last: Define how the last line of a block or a line, right before a forced line break, is aligned.
  • text-orientation (en-US): Define the orientation of the text in a line.
  • overflow-wrap: Specify whether or not the browser may break lines within words in order to prevent overflow.
  • writing-mode: Define whether lines of text are laid out horizontally or vertically and the direction in which subsequent lines flow.

Font shorthand

Many font properties can also be set through the shorthand property font. These are written in the following order: font-style, font-variant (en-US), font-weight, font-stretch (en-US), font-size, line-height, and font-family.

Among all those properties, only font-size and font-family are required when using the font shorthand property.

A forward slash has to be put in between the font-size and line-height properties.

A full example would look like this:

font: italic normal bold normal 3em/1.5 Helvetica, Arial, sans-serif;

Active learning: Playing with styling text

In this active learning session, we don’t have any specific exercises for you to do: we’d just like you to have a good play with some font/text layout properties, and see what you can produce! You can either do this using offline HTML/CSS files, or enter your code into the live editable example below.

If you make a mistake, you can always reset it using the Reset button.

<div class="body-wrapper" style="font-family: 'Open Sans Light',Helvetica,Arial,sans-serif;">
  <h2>HTML Input</h2>
  <textarea id="code" class="html-input" style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;">
<p>Some sample text for your delight</p>
  </textarea>

  <h2>CSS Input</h2>
  <textarea id="code" class="css-input" style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;">
p {

}
</textarea>

  <h2>Output</h2>
  <div class="output" style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;"></div>
  <div class="controls">
    <input id="reset" type="button" value="Reset" style="margin: 10px 10px 0 0;">
  </div>
</div>
const htmlInput = document.querySelector(".html-input");
const cssInput = document.querySelector(".css-input");
const reset = document.getElementById("reset");
let htmlCode = htmlInput.value;
let cssCode = cssInput.value;
const output = document.querySelector(".output");

const styleElem = document.createElement('style');
const headElem = document.querySelector('head');
headElem.appendChild(styleElem);

function drawOutput() {
  output.innerHTML = htmlInput.value;
  styleElem.textContent = cssInput.value;
}

reset.addEventListener("click", function() {
  htmlInput.value = htmlCode;
  cssInput.value = cssCode;
  drawOutput();
});

htmlInput.addEventListener("input", drawOutput);
cssInput.addEventListener("input", drawOutput);
window.addEventListener("load", drawOutput);

Test your skills!

You’ve reached the end of this article, and already did some skill testing in our Active Learning section, but can you remember the most important information going forward? You can find an assessment to verify that you’ve retained this information at the end of the module — see Typesetting a community school homepage.

This assessment tests all the knowledge discussed in this module, so you might want to read the other articles before moving on to it.

Summary

We hoped you enjoyed playing with text in this article! The next article will give you all you need to know about styling HTML lists.

  • Обзор: Styling text
  • Далее

In this module

29.12.2019CSS, Веб-технологии

Замена текста в основном прорабатывается на стороне сервера. Но в некоторых случаях, когда у нас нет контроля над сервером или мы работаем с ограничениями, замена текста с помощью CSS может быть выбором.

Метод 1: Использование псевдоэлементов и модификатора видимости с абсолютным позиционированием
Для начала мы обертываем текст и присваиваем ему класс. Этот метод требует очень мало разметки.

<p class="toBeReplaced">Old Text</p>

Текст «Старый текст» должен быть сначала скрыт, а новый текст должен располагаться точно там, где был старый текст. Для этого мы сначала изменим видимость этого текста с помощью CSS на скрытый .

.toBeReplaced {
    visibility: hidden;
    position: relative;
}

Затем мы добавляем новый текст в точно такую же позицию, используя псевдоэлементы и соответствующее явное позиционирование.

.toBeReplaced:after {
    visibility: visible;
    position: absolute;
    top: 0;
    left: 0;
    content: "This text replaces the original.";
}

Обратите внимание, что здесь используется псевдоэлемент after . Мы используем модификатор видимости еще раз, чтобы показать новый текст. Атрибут содержимого содержит новый текст.

Пример:

<html>

<head>

    <style>

        .toBeReplaced {

            visibility: hidden;

            position: relative;

        }

        .toBeReplaced:after {

            visibility: visible;

            position: absolute;

            top: 0;

            left: 0;

            content: "This text replaces the original.";

        }

    </style>

</head>

<body>

    <p class="toBeReplaced">Old Text</p>

</body>

</html>

Выход:

This text replaces the original.

Способ 2. Использование псевдоэлементов и модификатора видимости с тегом <span>
В этом методе нам нужно немного больше разметки, но нам больше не нужно указывать абсолютное позиционирование для нашего нового текста. Мы переносим текст с помощью тегов <span>.

<p class="toBeReplaced"><span>Old Text</span></p>

В этом методе мы используем дочерний элемент для переноса текста, то есть текст теперь находится внутри тегов <p> и <span>. Поэтому мы можем использовать CSS-атрибут display: none, чтобы скрыть текст в элементе <span>. Затем мы можем просто заменить текст, как мы это делали в предыдущем методе, без указания какого-либо позиционирования.

.toBeReplaced span {
    display: none;
}

.replaced:after {
    content: "This text replaces the original.";
}

Пример:

<html>

<head>

    <style>

        .toBeReplaced span {

            display: none;

        }

        .toBeReplaced:after {

            content: "This text replaces the original.";

        }

    </style>

</head>

<body>

    <p class="toBeReplaced"><span>Old Text</span></p>

</body>

</html>

Выход:

This text replaces the original.

Рекомендуемые посты:

  • Как выделить весь текст в текстовом вводе HTML при нажатии с использованием JavaScript?
  • JavaScript | Заменить () метод
  • Как заменить innerHTML div, используя jQuery?
  • CSS | Текстовые эффекты
  • CSS | Форматирование текста
  • Как заменить все точки в строке, используя JavaScript?
  • HTML | Расположение DOM метод replace ()
  • Как заменить элемент из массива в JavaScript?
  • Как заменить символ по определенному индексу в JavaScript?
  • Как заменить обычный URL ссылкой, используя JavaScript?
  • CSS | Свойство text-justify
  • CSS | текстовое оформление недвижимости
  • HTML | Форматирование текста
  • Как вертикально отцентрировать текст с помощью CSS?
  • CSS | Свойство text-align

Как заменить текст на CSS?

0.00 (0%) 0 votes

Here we look at properties that can assist in styling your text

  • Text color
  • Text alignment
  • Text decoration
  • Text transform
  • Text shadow
  • Text indentation
  • Letter spacing
  • Line height
  • Word spacing

Text Color

The color property is used to set the text color. To specify the color you can use a color name (red), a HEX value (#ff0000) or an RGB value (rgb (255,0,0) ).

Example of the color property:.

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <p style="color:#ff0000">This is some paragraph in red.</p>
  </body>
</html>

Result

Text Color

Text Alignment

Alignment property is used for aligning text inside an element left, right, center, etc.

Text alignment has four values:

  • Left (text-align: left) — aligns the text to the left
  • Right (text-align: right) — aligns the text to the right
  • Center (text-align: center) — puts the text in center of the page
  • Justify (text-align: justify) — stretches the line of text to align both the left and right ends (like in magazines and newspapers)

Browsers by default align text to the left, and if there is need to align text to the right or put it in the center, we should use the corresponding value.

Example of the text-alignment property:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <p>This is some paragraph</p>
    <p style="text-align:center">Some paragraph with value center.</p>
    <p style="text-align:right">Some paragraph with value right.</p>
    <p style="text-align:justify">Some paragraph with value justify.</p>
  </body>
</html>

Text Decoration

Text decoration is used for setting the decoration of the text. In CSS3, it is a shorthand for the CSS text-decoration-line, CSS text-decoration-color and CSS text-decoration-style properties.

Decoration property is used to specify line decorations added to the text. The following values are valid for text-decoration property.

  • Overline (text-decoration:overline) — each line of text has a line over it
  • Underline (text-decoration:underline) — each line text is underlined
  • Line-through (text-decoration:line-through) — each line of text has a line going through it
  • None (text-decoration:none) — no text decoration is applied

Example of the text-decoration property:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <a style="text-decoration:none">This is link without underline</a>
    <h1 style="text-decoration:overline">Heading with value overline.</h1>
    <p style="text-decoration:line-through">Some paragraph with value line-through.</p>
    <a style="text-decoration:underline">Some hyperlink with value underline.</a>
  </body>
</html>

Result

Text Decoration

Text Transform

Transform property is used for controlling text capitalization. It means that you can set your text to be uppercase, lowercase, or capitalized (title case).

Transform property has the following values:

  • Uppercase (text-transform: uppercase) — converts all characters to uppercase
  • Lowercase (text-transform: lowercase) — converts all characters to lowercase
  • Capitalize (text-transform: capitalize) — converts the first character of each word to uppercase

Example of the text-transform property:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <p style="text-transform:uppercase">Paragraph with uppercase.</p>
    <p style="text-transform:lowercase">Paragraph with lowercase.</p>
    <p style="text-transform:capitalize">Paragraph with capitalize.</p>
  </body>
</html>

Result

Text Transform

Text Shadow

We use the text-shadow property when we want to give shadow to our text.

Shadow property is used to apply various shadow effects to the text. It accepts a list of values. Each item in the list can have two and more comma-separated values.

The text shadow property syntax can look like

text-shadow: h-shadow v-shadow blur color

Here you can see examples of text shadow.

Text Indentation

Text indentation property is used for specifying the length of empty space of the first line in a text block. The values below are valid for this property:

  • Length , which specifies the indentation in px, pt, cm, em, etc. The default value is 0.
    Negative values are allowed.
  • Percentage — which Specifies the indentation in percentage of the width of the containing block.
  • Each-line, when the indentation affects the first line as well as each line after a forced line break, but does not affect lines after a soft wrap break.
  • Hanging, which inverts which lines are indented. The first line is not indented.
  • Initial, which makes the property use its default value.
  • Inherit, which inherits the property from its parent’s element.

Example of the text-indent property:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      p {
        text-indent: 100px;
        line-height: 24px;
        font-size: 16px;
      }
    </style>
  </head>
  <body>
    <h2>Text Indentation Example</h2>
    <p>
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
  </body>
</html>

CSS letter-spacing property allows to define the spaces between letters/characters in a text. The following values are supported by this property:

  • Normal, which means that there won’t be extra spaces between characters. It is the default value of this property.
  • Length, which defines an extra space between characters. Negative values are allowed.
  • Initial, which makes the property use its default value.
  • Inherit, which inherits the property from its parent’s element.

Example of the letter-spacing property:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      p {
        text-indent: 100px;
        line-height: 24px;
        font-size: 16px;
        letter-spacing: 5px;
      }
      h3 {
        letter-spacing: -1px;
      }
    </style>
  </head>
  <body>
    <h2>Example of letter-spacing property</h2>
    <p>
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
    <h3>
      Here is some text with letter-spacing property.
    </h3>
  </body>
</html>

The line-height property defines the line-height. It is used to set the leading of lines of a text. If the line-height value is greater than the value of the font-size of an element, the difference will be the leading of text. Here are the values supported by this property:

  • Normal, which defines a normal line height. It is the default value of this property.
  • Length, which defines a fixed line height in px, cm etc.
  • Number, which defines a number which is multiplied with the current font size to set the line height.
  • %, which defines a line height in percent of current font size.
  • Initial, which makes the property use its default value.
  • Inherit, which inherits the property from its parent’s element.

Example of the line-height property:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      p {
        line-height: 30px;
      }
      h3 {
        line-height: 1;
      }
    </style>
  </head>
  <body>
    <h2>Example of line-height property</h2>
    <p> Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book. </p>
    <h3>
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </h3> 
  </body>
</html>

With the help of the CSS word-spacing property we can change the space between the words in a piece of text, not the individual characters. It supports the values below:

  • Normal, which specifies normal word spacing. This is the default value of this property.
  • Length, which specifies an extra word spacing. Can be specified in px, pt, cm, em, etc. Negative values are valid.
  • Initial, which makes the property use its default value.
  • Inherit, which inherits the property from its parent’s element.

Example of the word-spacing property:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      p {
        word-spacing: 1em;
      }
      h3 {
        word-spacing: -3px;
      }
      span {
        display: block;
        word-spacing: 3rem;
      }
    </style>
  </head>
  <body>
    <h2>Example of word-spacing property</h2>
    <p>
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
    <h3>
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </h3>
    <span>
    Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs.
    </span>
  </body>
</html>

Положительное восприятие веб-сайта пользователем зависит не только от смыслового содержания текста, но и от его оформления.

Существует вероятность, что человек не станет читать даже очень грамотно и хорошо написанный, но не оформленный или плохо оформленный текст, поэтому следует уделить особое внимание вопросу удобочитаемости.

CSS предоставляет довольно обширные возможности, позволяющие кардинально изменить внешний вид вашего текста с помощью различных цветовых решений, размера строки и т.д.

  • Визуальное оформление текста в CSS
  • Цвет текста в CSS
  • Размер текста в CSS
  • Отступ текста в CSS
  • Жирный и наклонный текст в CSS
  • Тень текста в CSS
  • Выравнивание текста в CSS

В CSS оформление текста осуществляется с помощью параметра text-decoration, который может принимать следующие значения:

  • blink — мерцающий текст;
  • none — значение по умолчанию, оформление отсутствует;
  • overline — линия расположена над текстом;
  • underline — подчеркнутый линией текст;
  • line-through — текст, зачеркнутый линией;
  • inherit — в данном случае text-decoration наследует значение родительского элемента.

Пример:

<a href="index.html" style="text-decoration:none">Текст ссылки</a>
<a href="index.html" style="text-decoration:overline">Текст ссылки</a>
<a href="index.html" style="text-decoration:underline">Текст ссылки</a>
<a href="index.html" style="text-decoration:line-through">Текст ссылки</a>
<a href="index.html" style="text-decoration:none">Текст ссылки</a>

В окне браузера данный пример будет выглядеть следующим образом:

Визуальное оформление текста в CSS

Изменить цвет текста, расположенного внутри HTML элементов можно с помощью CSS свойства color.

Способы задания могут быть следующими:

  • При помощи названия цвета (например, red, green, blue, white);
  • При помощи значения RGB (например, rgb(221,102,212));
  • При помощи шестнадцатеричного цветового значения (например, #ff00aa).

Пример:

<html>
<head>
<title>CSS цвет</title>
</head>
<body>
<p style="color:red">Текст 1 Текст 2 Текст 2</p>
<p style="color:rgb(245,100,255)">Текст 2 Текст 2 Текст 2</p>
<p style="color:#7722aa">Текст 3 Текст 3 Текст 3</p>
</body>
</html>

Визуальное оформление, реализованное с помощью приведенного выше кода, выглядит следующим образом:

Цвет текста в CSS

CSS свойство font-size позволяет задать размер текста.

Единицами измерения могут быть:

  • Пиксели (например, 14px);
  • Пункты (например, 20pt);
  • Проценты (например, 50%);
  • Ключевые слова small, large и т.п.

Пример:

<head>
<style type="text/css">
p {font-size:14px}
p.big {font-size:20pt}
</style>
</head>
<p>Текстовая строка размером 14 пикселей.</p>
<p class="big">Текстовая строка размером 20 пунктов.</p>

Визуальное представление приведенного выше кода выглядит следующим образом:

Размер текста в CSS

Изначальная концепция HTML не предполагала отступы, выделяя абзацы лишь вертикальным расстоянием, а множество пробелов перед строкой браузер преобразует в один.

Однако в CSS данная проблема решается с помощью свойства text-indent.

Пример:

<html>
<title>Отступ текстовой строки</title>
</head>
<body>
<p>Текст без отступа.</p>
<p style="text-indent:110px">Текст с отступом слева 110 пикселей</p>
</body>

Визуальное отображение кода:

Отступ текста в CSS

С помощью атрибута CSS font-weight определяется жирность шрифта.

Данный атрибут может принимать следующие значения:

  • normal — обычный;
  • lighter — более светлый;
  • bold — жирный;
  • от 100 до 900, где 100 — самый тонкий шрифт, а 900 — самый толстый.

Пример:

<html>
<head>
<title>Стили шрифта</title>
</head>
<body>
<p style="font-weight: normal">текст текст текст текст</p>
<p style="font-weight: bolder">текст текст текст текст</p>
<p style="font-weight: 600">текст текст текст текст</p>
</body>
</html>

В браузере данный код выглядит следующим образом:

Жирный и наклонный текст в CSS

CSS свойство text-shadow позволяет задать тексту тень. Данное свойство содержит в себе целый перечень эффектов: цвет, смещение вправо, смещение вниз, радиус пятна тени.

В том случае, если цвет тени не задан, используется цвет текста.

Пример:

<head>
<title> тень текста в CSS </title>
</head>
<body>
<h1 style="text-shadow:#cccccc -17px -8px 6px">Текст с тенью
</h1>
</body>

Представленный выше код в браузере выглядит следующим образом:

Тень текста в CSS

Выравнивание текста по горизонтали задаётся свойством text-align, которое может принимать следующие значения:

  • left — выравнивание по левому краю;
  • right — выравнивание по правому краю;
  • center — выравнивание по центру;
  • justify — выравнивание по всей ширине.

С помощью свойства vertical-align выполняется выравнивание текста по вертикали.

Данное свойство может принимать следующие значения:

  • baseline — выравнивание линии элемента по базовой линии родительского элемента;
  • middle — выравнивание средней элементной точки по базовой линии родительского элемента;
  • text-top — выравнивание верхней части элемента по верху шрифта родительского элемента;
  • top — выравнивание верха элемента по верхней части самого высокого элемента строки;
  • sub, super — отображение элемента в виде нижнего и верхнего индексов соответственно.

Пример:

<title>Выравнивание текста по вертикали</title>
</head>
<body>
<table height="80" cellpadding="10" border="1">
<tr>
<td style="vertical-align:top">Текст 1</td>
<td style="vertical-align:bottom">Текст 2</td>
<td style="vertical-align:middle">Текст 3</td>
</tr>
</table>

Выравнивание текста в CSS

Таким образом, возможности CSS позволяют произвести практически любые манипуляции с оформлением текста на веб-сайте для улучшения его восприятия пользователями.

Желаем удачи в изучении веб-дизайна!

Понравилась статья? Поделить с друзьями:
  • Как изменить текст на клавиатуре на телефоне
  • Как изменить текст footer joomla
  • Как изменить текст canvas tkinter
  • Как изменить текст на кириллицу
  • Как изменить текст на картинке через фотошоп