How to save text inside a div, always in the middle?

I am trying to make text in the middle of a volatile DIV. Here is an example:

CSS

#rightmenu { position: absolute; z-index: 999999; right: 0; height: 60%; text-align: center; } 

HTML

 <div id="rightmenu">This text should be center aligned and in the middle of the resizable rightmenu</div> 

I tried to make the class contain text with "margin-top and margin-bottom" as in auto, but it doesn't work.

+4
source share
5 answers

If you do not need IE7 support, you can do it as follows:

HTML:

 <div id=wrap> <div id=inside> Content, content, content. </div> </div> 

CSS

 #wrap { /* Your styling. */ position: absolute; z-index: 999999; right: 0; height: 60%; text-align: center; /* Solution part I. */ display: table; } /* Solution part II. */ #inside { width: 100%; height: 100%; display: table-cell; vertical-align: middle; } 

Code: http://tinkerbin.com/ETMVplub

If you're fine with JavaScript, you can try this jQuery plugin: http://centratissimo.musings.it/ , but since it also does not support IE7 the CSS solution is probably better.

+9
source

Replace height: 60%; on padding: 30% 0; .

+1
source

Flexbox really changed the game with the alignment of elements in a fluid manner. Define your container element as display: flex , and then align your inner child elements that you would use justify-content: center; align-items: center; justify-content: center; align-items: center;

 .container { position: absolute; top: 0; right: 0; bottom: 0; left: 0; display: flex; justify-content: center; align-items: center; } .parent { height: 500px; width: 500px; position: relative; } <div class="parent"> <div class="container"> <p>Hello</p> <p>World</p> </div> </div> 

You will notice that "Hello" and "World" will be centered vertically and horizontally inside the .container element.

+1
source

If you want the text to be horizontally centered in the div, 'text-align: center;' your friend. If you want it to be vertically centered; wrap the contents inside the inner div, and then use "margin: auto" for that inner div. Of course, you will need to give the inner div the width; otherwise the horizontal center will not work.

'valign = "middle"' also works in tables if tables are an option (otherwise not recommended)

0
source

Check if this is required:

 <html> <head> <style type="text/css"> div { height: 100px; width: 100px; background: #ccc; text-align: center; } p { line-height: 100px; } </style> </head> <body> <div> <p>centered</p> </div> </body> </html> 
0
source

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


All Articles