Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set dynamic width with only CSS?

Tags:

css

dynamic

width

I have a title (h1) which is centered on the page. I want to add lines to the left and right of the title, so that they fill the rest of the page's width. However, I want the lines to adapt to the title's width, which is dynamic. So, I want the line's width to be dynamically calculated.

Here's an example of what I'm trying to accomplish: http://jsfiddle.net/cAEqE/1/

In the example I set the lines' width to 35% so they could get the effect that I want. However, if the title is longer, it will break into 2 lines, and I don't want that to happen.

My boss told me to avoid javascript, so it would be excellent to use only CSS. However, if this turns out to be impossible, I will turn to good old jQuery. Cheers!

Edit: the website has a background-image, so I can't use a background on the h1. Thanks!

like image 225
Cthulhu Avatar asked Mar 26 '12 10:03

Cthulhu


2 Answers

You can write like this:

CSS

h1 {
    font-size: 26px;
    text-align:center;
    display:inline-block;
    *display:inline;/* For IE7*/
    *zoom:1;/* For IE7*/
    background:#fff;
    padding:0 10px;
}

#title {
    text-align:center;
    border-bottom:1px solid #97999C;
    height:10px
}

HTML

<div id="title">
    <h1>TITLE TEST</h1>
</div>

Check this http://jsfiddle.net/cAEqE/27/

UPDATED

Check this http://jsfiddle.net/cAEqE/63/

like image 151
sandeep Avatar answered Oct 25 '22 17:10

sandeep


Instead of using divs for the lines, you should use a background image on the parent div.

For example, your HTML would be much simpler:

<div id="content">
    <h1>TITLE TEST</h1>
</div>​

And your CSS would be:

h1 {
    font-size: 26px;
    background-color: white;
    display:inline;
    padding:0 30px;
}

#content {
    text-align:center;
    width:100%;
    background:transparent url(https://jira.atlassian.com/s/en_UKtovngv/725/4/1.0/_/images/mod_header_bg.png) repeat-x left center;
    margin:0;
    padding:0;
}

I've stolen a fair bit of this code from Jira which does basically what you're after.

like image 29
Gareth Bowen Avatar answered Oct 25 '22 17:10

Gareth Bowen