I have a div with absolute position which has a dynamic width width:auto; in the css style.
the content of this div is dynamic texts... which means whatever I type into an input field, it will be displayed inside this div.
when the div is empty or has only a 2-3 letters inside it, it is centered... but when there are more letters or words inside the div, the width of the div expands to show the contents and this will make the div to not to be centered anymore..
I did try text-align:center; in the CSS style and this did not work. I also tried margin: 0 auto;.
Is there any way using javascript or jquery to calculate the content of the div and center it accordingly?
OR
is there anyway, to expand the Div both right and left ways so the middle of the Div is always centered? as currently the Div expands from the right side only as there are more letters in it!
Here is my CSS for this dynamic div:
#BOTtext{
position: absolute;
width: auto;
height: 16px;
left: 47%;
top: 140px;
z-index: 1000000000;
background-color: #f7f7f7;
margin: 0 auto;
}
Thank you in advance.
Check this http://jsfiddle.net/AyBtT/
Javascript
$(function () {
$("#txt").keyup(function () {
$("#BOTtext").html($(this).val());
adjust();
});
$(window).resize(adjust);
adjust();
function adjust() {
$("#BOTtext").css("left", ($(window).width() - $("#BOTtext").width())/2);
}
});
HTML
<div id="BOTtext">Type in the text field</div>
<input id="txt"/>
try with a negative transform: translateX
#BOTtext{
position: absolute;
top: 140px;
left: 50%;
height: 16px;
z-index: 1000000000;
background-color: #f7f7f7;
-webkit-transform: translate3d(-50%, 0, 0);
-moz-transform: translate3d(-50%, 0, 0);
transform: translate3d(-50%, 0, 0);
}
Example on codepen: http://codepen.io/anon/pen/isDHa/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With