How to center a paragraph of text on a particular

2020-02-27 07:24发布

I have a passage that is centered on the page, like this:

 _________________________
|                         |
| Once upon a time, there |
|   lived a squirrel who  |
|  lived in the middle of |
|       the forest.       |
|_________________________|

I need to adjust the centering such that a specifically marked word is horizontally centered on the page. In this example, the word "who" is centered:

 _________________________
|                         |
|        Once upon        |
|  a time, there lived a  |
|  squirrel who lived in  |
|    the middle of the    |
|         forest.         |
|_________________________|
  • The word who is marked in the HTML with a <div> tag, i.e. <center>Once upon a time, there lived a squirrel <div style="centered">who</div> lived in the middle of the forest.</center>.
  • The HTML appears in an application in which I have little control over editing the HTML itself (the text is already marked with CSS style tags), but can modify the style sheet or add code, such as JavaScript to the header to modify how that style is rendered.

How can I center a passage on a particular word in HTML, CSS, or JavaScript?

16条回答
我想做一个坏孩纸
2楼-- · 2020-02-27 08:20

You can very simply do it in this way.

Fiddle Demo

Code:

<div style="position:absolute; left:50%; margin-left:-108px;">
 <pre>
 _________________________
|                         |
| Once upon a time, there |
|   lived a squirrel who  |
|  lived in the middle of |
|       the forest.       |
|_________________________|
    </pre>
    </div>
查看更多
时光不老,我们不散
3楼-- · 2020-02-27 08:20

Do you have a CSS file linked? If you do, I would recommend changing the div tag to

<div class="who">who</div>

In the CSS file, you should have

.who { 
  text-align: center; 
}

It is also possible that you force the html to include spaces with the following code: &nbsp (Include a semicolon at the end, it won't let me do it). So instead of having one space, you can have multiple non-breaking spaces.

查看更多
老娘就宠你
4楼-- · 2020-02-27 08:28
<div>
<p class ="center"> Once upon </p>
<p class ="center">a time, there lived a</p><p class = "center">squirrel who  
 lived in</p><p class = "center"> the middle of </p>
<p class = "center">
   the forest. 
</p>
</div>


  Try This with css code:

  .center{
    text-align:center;
    letter-spacing:2px;

   }
查看更多
不美不萌又怎样
5楼-- · 2020-02-27 08:29

Use CSS more specifically in the parent elements to target your words alignment. For example if there is a paragraph (p) and then after it their are two divs (div) then use the specific parent css property like this.

p div div {text-align:center; display:inline-block;} 

that's it and it will do the work for you. Similarly you can target your given example with

center div {text-align:center; display:inline-block;}
查看更多
登录 后发表回答