开发者

Center text in div having a div inside of it

开发者 https://www.devze.com 2023-02-12 03:31 出处:网络
I have this code: <div style=\"border:1px solid #afafaf;background-color:#efefef;width:100px;height:14px;\">

I have this code:

<div style="border:1px solid #afafaf;background-color:#efefef;width:100px;height:14px;">
    <div style="text-align:center;width:50px;height:14px;background-color:green;">
        50%
    </div>
</div>

How can i put the 50% in the middle if the 1st DIV , the 2nd div might have width of 0 to 100 px (progress b开发者_Go百科ar)


Live Demo

  • I added position: relative to your outer div.
  • I added a new text div, which is absolutely positioned over the progress bar.
  • See http://css-tricks.com/absolute-positioning-inside-relative-positioning/

Whatever width your progress bar has, it won't affect the text div.

HTML:

<div style="border:1px solid #afafaf;background-color:#efefef;width:100px;height:14px;position:relative">
    <div style="text-align:center;width:50px;height:14px;background-color:green;"></div>
    <div id="text">50%</div>
</div>

CSS:

#text {
    position: absolute;
    width: 100%;
    top: 0;
    left: 0;
    text-align: center
}


For example have a third div with margin-left:auto;margin-right:auto which centers this div into the middle

0

精彩评论

暂无评论...
验证码 换一张
取 消