Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

css

I'm trying to make text stay in the middle of a resizable DIV. Here's the 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've tried to make a Class to contain the text with the "margin-top and margin-bottom" both on auto, but doesn't work.

like image 705
rmz Avatar asked May 10 '12 17:05

rmz


People also ask

How do I keep text in the center of a div?

You can do this by setting the display property to "flex." Then define the align-items and justify-content property to “center.” This will tell the browser to center the flex item (the div within the div) vertically and horizontally.

How do I keep text in the center?

Select the text that you want to center. in the Page Setup group, and then click the Layout tab. In the Vertical alignment box, click Center.

How do you keep text in the middle in HTML?

The <center> tag was used in HTML4 to center-align text.


2 Answers

If you don't care about IE7 support, you can do it like that:

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;
}

The code: http://tinkerbin.com/ETMVplub

If you're OK with JavaScript you can try this jQuery plugin: http://centratissimo.musings.it/ but since it also doesn't seems to support IE7 the CSS solution is probably better.

like image 124
Mateusz Kocz Avatar answered Oct 02 '22 10:10

Mateusz Kocz


Flexbox has really changed the game with aligning elements in a fluid manner. Define your container element to be display: flex and then to align your inner children you would use 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'll notice that "Hello" and "World" will both be vertically and horizontally centered within the .container element.

like image 39
domdambrogia Avatar answered Oct 02 '22 08:10

domdambrogia