How can I focus on something if I don’t know in advance what width is?

I am trying to center a paragraph tag with some text in it in a div, but I cannot center it using margin: 0 auto without specifying a fixed width for the paragraph. I don’t want to specify a fixed width, because I will have dynamic text included in the paragraph tag, and it will always differ in width, based on how much text it is.

Does anyone know how I can center a paragraph tag inside a div without specifying a fixed width for the paragraph or without using tables?

+4
source share
8 answers

Here's how to do it using a stylesheet.

Style sheet:

div.center-content { text-align: center; } div.center-content p { text-align: left; margin-left: auto; margin-right: auto; } 

HTML:

 <div class="center-content"> <p>Lorem ipsum dolor sit amet</p> </div> 
+9
source

In addition to the text-align property

to center elements inside block elements such as div

use css for example

  margin: auto

something like the one below

For vertical centering, it is better to use tables (in most cases, this is the only cross-browser compatible solution)

you can use

  "text-align: center"  

  "vertical-align: middle" 
+1
source

I think the best way is to contain an element in a block level element and do:

 .innerElement {margin:0 auto} 

Given that they are both block level elements that do not have a float parameter, it should work fine!

+1
source

here is a good workaround for centering a div without width .

without tables and works in any browser!

+1
source

Try using inline CSS:

 <p style="text-align: center;">Lorem ipsum dolor sit amet</p> 

Or using only HTML

 <p align="center">Lorem ipsum dolor sit amet</p> 
0
source

if the div has a set width, all you need is

.myDiv {text-align: center; }

Also listen to comments on the garage. in no case use inline css.

Also another dirty fix for this if you have other things in the center of the div:

you can always:

$ ('. youParagraph or .otherContent'). wrap ('');

Obviously, do not practice this if you are working in a large team, and sharing problems is a problem.

Hope this helps.

0
source

Eh, auto fields should have a set width, since the default is a block level element such as

will expand to the full available width.

If you do not support IE <8, you can simply set {display: table; margin: 0 auto; }

Otherwise, if your element is surrounded by block level elements, you can do p {display: inline-block; } p {display: inline; } html> / ** / body p {display: inline-block; } (the last two rules for IE and resetting the IE fix for smart browsers), then apply {text-align: center; } in the container.

As already mentioned, see http://haslayout.net/css-tuts/Horizontal-Centering for more information.

Hooray! Zoffix znet

0
source

Source: https://habr.com/ru/post/1285892/


All Articles