Is there a CSS selector to select text (inline blo

2019-06-16 06:58发布

问题:

Can a CSS rule select the portion of a box which contains text (or an inline block)?

For example, an HTML fragment like <p>The quick brown fox jumped over the lazy dog</p> might be laid out like this:

+--------------------------+
|  The quick brown fox     |
|  jumped over the         |
|  lazy dog                |
+--------------------------|

If I create a CSS rule like p { background: red } then the whole box/rectangle will have a red background, including the "whitespace" at the end of each line.

Is there a way to specify a selector such that, on each line, only the actual text has a red background?

I notice that by default the cursor changes from 'arrow' to 'i-beam' when it's actually over text; when it's elsewhere within the paragraph box, not over text, then it's an arrow not an i-beam.

If I specify an explicit rule like p { cursor: crosshair } then it's effective everywhere within the rectangular box. Again, is it possible to have a rule that's selected only when the cursor is actually over text?

回答1:

What you can do is to wrap the text in a span element, and then set the background and cursor properties to it.



回答2:

There's no way to do exactly what you want as far as I am aware because CSS selectors do not match text nodes. You'd have to wrap the text in a span and then style the span.



回答3:

jsut a simple code snippet to help maybe:

added a style or two extra..not necessary though.. hope it helps..

p {
    background-color: gray;
    width: 700px;
    height: 500px;
    margin:auto;
}

span {  
    background-color: red;
    width: 500px;
    height: 200px;
    border: 2px blue;
    border-style: dotted dashed;
    font-size: 2em;
    display: block;
    margin:auto;
}