简体   繁体   中英

Make a div half the width of another div

What i'm trying to do is make the title of a blog post exactly half the width of the blog description and align itself at 50% of the width of the blog description.

This is what i tried in JS:

var post_title_width = document.getElementById("post_desciption").offsetWidth;

var post_title_width = post_description * 0.5; document.getElementbyId("post_title").style.width = post_title_width;

HTML:

    <div class="post">
    <span class="post_title">This is a test title, testing some javascript...........</span><br>
    <span class="post_description">Hello this is a test description right here, just to test some code im trying to do</span>   
    </div>

I am not using css because i want to test javascript and learn how to use it efficiently.

Try this ( example ):

HTML

<div id="head"><div id="half"></div></div>

CSS

#head {
    width: 300px;
    height: 100px;
    background: purple;
}
#half {
    height: 100%;
    background: green;
}

JS

document.getElementById("half").style.width = document.getElementById("head").offsetWidth / 2 + 'px';

JS for margin inner block at the center of it's countainer try to use this ( example ):

document.getElementById("half").style.marginLeft = (document.getElementById("head").offsetWidth - document.getElementById("half").offsetWidth) / 2 + 'px';

If you really want to do it in javascript, you've got a few problems:

  1. You're trying to target class names with getElementbyId
  2. Your variable names are messed up
  3. Spans are not block elements, so setting the width isn't applicable unless you set overflow and change the display to block or inline-block

http://jsfiddle.net/cmweU/

var post_description = document.getElementsByClassName("post_description")[0],
    post_description_width = post_description.offsetWidth,
    post_title_width = ( post_description_width * 0.5 ) + "px"; 

document.getElementsByClassName("post_title")[0].style.width = post_title_width;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM