Posts

Showing posts from June, 2011

antlr3 - what does | mean when there is no right side in antlr -

i saw in antlr grammar today not sure means. wish google let me search characters... resultlist: (star | attributelist |) -> ^(result attributelist? star?); notice second "|" character has no right side element? mean? thanks, dean it means matches nothing. following, more verbose rule, same: resultlist : star -> ^(result star) | attributelist -> ^(result attributelist) | /* nothing */ -> result ; i think version above more clear, , easier evaluate later on sine there no 2 optional child nodes, attributelist , star , need check presence.

php - Manipulate image without saving it -

i want things on image uploaded user. until now, is: move_uploaded_file imagecreatefrompng how can manipulate without saving it? when file uploaded, has stored somewhere in server's /tmp/ folder. load image there using $_files['name']['tmp_name'] . for example: $image = imagecreatefrompng($_files['blarg']['tmp_name']); will load uploaded file (called blarg ) it's temporary storage place under /tmp/php-12bja . don't need call move_uploaded_file() , , image doesn't need saved disk.

sql - TSQL retrieve maximum row based on a combination of the largest of other columns -

i have table in sql server 2012 contains patch notes different versions of software. table looks this: versionid int primarykey identity major tinyint minor tinyint revision tinyint patchnotes nvarchar(max) i need retrieve row recent version based on major, minor , revision. example, version 1.1.4 comes after version 1.1.3 before version 1.2.1. would have ideas on how write query in tsql this? if maybe push me in right direction without completing entire query, i'd appreciative. trying learn , that! i order 3 fields descending , take 1 record: select top 1 versionid, major, minor, revision, patchnotes versions order major desc, minor desc, revision desc multiple sort columns can specified. sequence of sort columns in order by clause defines organization of sorted result set. result set sorted first column , ordered list sorted second column, , on.

Horizontally scroll page with mouse move -

i have simple list of images here floated horizontally off right of page. http://www.ttmt.org.uk/forum/gallery/ i can view image mouse scrolling left , right. how can scroll page moving mouse left , right without scrolling. so gallery position determined position of mouse on page. <!doctype html> <html> <head> <title>title of document</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/3.4.1/build/cssreset/cssreset-min.css"> <style type="text/css"> ul#gallery { margin:100px 0 0 0; float:left; height:500px; margin-right:-20000px; } ul#gallery li{ display:inline; } ul#gallery li img{ float:left; height:100%; } #header{ position:fixed; margin:20px 0 0 20px; } #header img, #header ul#info{ float:left; } #header ul#info{ margin:5px 0 0 5...

mysql - PHP If / else user exists on database set variable to 0 or 1 -

i have code check if user exists in database. want assign $account 1 if exits, , 0 if doesn't. thought code work setting $account 0 think im missing trick. appreciated. $con = mysql_connect(db_host, db_user, db_pass) or die("couldn't make connection."); if (!$con) { die('could not connect: ' . mysql_error()); } mysql_select_db(db_name, $con); $sql="select user_name users"; $result = mysql_query($sql) or die(mysql_error()); $row = mysql_fetch_assoc($result); if ($row['user_name'] == '$user_name'){ $account = 1; }else{ $account = 0;} thanks you can't put variables in string if use single quotes ' (plus it's not necessary!). below rectifies issue, , shortens if/else statement one-liner. $account = $row['user_name']==$user_name ? 1 : 0;

c# - Call StaticFileHandler -

i have httphandler mapped aspnet_isapi.dll perform custom authentication check on static files (.pdf files) using iis 7.5 in classic mode: void ihttphandler.processrequest(httpcontext context) { if(!user.ismember) { response.redirect("~/login.aspx?m=1"); } else { //serve static content } } the above code works fine, except else statement logic. in else statement, want allow staticfilehandler process request, haven't been able sort out. suggestions on how "hand off" file iis serve request normal staticfile request, appreciated. to answer question directly, can create staticfilehandler , have process request: // serve static content: type type = typeof(httpapplication).assembly.gettype("system.web.staticfilehandler", true); ihttphandler handler = (ihttphandler)activator.createinstance(type, true); handler.processrequest(context); but better idea might create http module instead of http handler: public class authenticationmodule : ihttpmodule { ...

ios - push notification inconsistencies -

working scenario: when run app xcode directly device can run push notification on server , works expected. non-working scenario: export app ipa , install app on device via itunes. when push notification server i'll error of error: unable send message id 1: invalid token (8). while writing post had thought , checked device id when came xcode install vs ipa install , different! code sending device id server: - (void)application:(uiapplication *)application didregisterforremotenotificationswithdevicetoken:(nsdata *)devicetoken { // can send here, example, asynchronous http request web-server store devicetoken remotely. // convert token single string nsstring *token = [[[devicetoken description] stringbytrimmingcharactersinset:[nscharacterset charactersetwithcharactersinstring:@"<>"]] stringbyreplacingoccurrencesofstring:@" " withstring:@""]; nsstring *post = [nsstring stringwithformat:[nsstring stringwithformat:@"token=%@", token]]...

html5 - html stream chunking file unknown size -

hi stream data webserver. here catch. data not exist on server retrieve live content server. not have size of file. how stream data.? i read pcm in chunks (of different sizes) convert ogg. send ogg header , ogg content down html5 audio tag or @ least want do. recap : server "a", there server "b" servers pcm data. client request comes audio tag html5 server data in server b( data not have size,constant streaming). a recieves pcm b converts ogg. sends along http response object binary data. any ideas. http/1.1 supports chunked encoding use case.

java - getView is never called for reasons beyond me -

i have custom list view adapter populated through asynctask, i'm calling notifydatasetchanged in onprogress function, , getcount() returns 10, yet list never shows, ive set breakpoint , determined getview() never called. ideas? ive tried hours , im stumped. ive done same thing in activity except 1 used viewholders, 1 holds text based data didn't bother. adapter: @override public view getview(int position, view convertview, viewgroup parent) { view row = convertview; if(row == null) { row = inflater.inflate(r.layout.podcastepisode, null); } podcastitem item = items.get(position); textview episodetitle = (textview)row.findviewbyid(r.id.episodetitle); textview episodedate = (textview)row.findviewbyid(r.id.episodedate); episodetitle.settext(item.title); episodedate.settext(api.formatpodcastdate(item.date)); return row; } my task: protected void onprogressupdate(podcastitem... progress) { addpodcastactivity.episodes.add(progress[0]); addpodcastactivity.adapter.notifydatasetchan...

haskell - Debugging unwanted strictness? -

i have problem don't know how reason about. ask if me specific problem, dawned on me ask more general question , better general understanding result. hopefully. here goes: it's obvious enough when program lazy, because end glaring issues space leaks, example. have opposite problem: program strict. trying tie knots , , find things attempt somehow defeat laziness need. general question is, how 1 debug unwanted strictness? for completeness, here's specific case: i'm in rws , writer component populates map, , reader component observes final state of map. can't strict map before i've finished populating it. appears no problem values in map, like: do m <- ask val <- m ! key dosomething val -- etc. but (!) fails using error , i'd instead prefer fail using monad's fail . i'd following: do m <- ask maybe (fail "oh noes") (dosomething) (lookup key m) this causes program <<loop>> , don't understand. doesn't seem ...

xml - Normalize whitespace in mixed-content elements, in XSLT 1.0 -

[edit: changed title better conceptualize question.] the value of attribute @xml:space can either "default" or "preserve" . xml specifies second means leaves first application. (i think have correct.) if application wants default implement xschema's collapse ? how xslt 1.0 this? i think built-in template processing text, is, <xsl:template match="text()"> <xsl:value-of select="."/> </xsl:template> would need replaced pseudo-code: <xsl:choose> <xsl:when test="../@xml:space='preserve'" <xsl:value-of select="."/> </xsl:when> <xsl:otherwise> if position(.)=1 output ltrim(value-of(.)) if position(.)=last() output rtrim(value-of(.)) if position(.)= 1 , last()=1 output normalize-space(.) </xsl:otherwise> </xsl:choose> this input then: <persname> man <forename>edward</forename> <forename>george</forename> <surname type=...

ios - Strange behaviours with stringWithFormat float -

(lldb) po [nsstring stringwithformat:@"%.1f", 0.01] (id) $21 = 0x003a2560 19991592471028323832250853378750414848.0 (lldb) po [nsstring stringwithformat:@"%.1f", 0.1] (id) $22 = 0x0de92240 -0.0 does understand behaviour here? i'm running on device. it's bug in lldb . if try same thing in gdb , works properly. suspect lldb passing low 32 bits of argument. ieee representation of 0.01 , of number it's printing these: 47ae147b3778df69 = 19991592471028323832250853378750414848.00 3f847ae147ae147b = 0.01 notice low 32 bits of 0.01 match high 32 bits of other number. the bug happens printf : (lldb) expr (void)printf("%.1f\n", 0.01) 19991592257096858016910903319197646848.0 <no result> it doesn't happen +[nsnumber numberwithdouble:] : (lldb) po [nsnumber numberwithdouble:0.01] (id) $3 = 0x0fe81390 0.01 so suspect bug in lldb 's handling of variadic functions. you can open bug report @ the llvm bugzilla and/or @ apple's bu...

Java Swing Timer with SQL -

i'm trying setup thread loops every 100ms every iteration querying table in sql database. here have in public static void main class. how can define connection outside of listener , call query in loop? // database credentials final string url = "jdbc:mysql://192.168.0.0/"; final string db = "db"; final string driver = "com.mysql.jdbc.driver"; final string table = "table"; public final connection conn = null; // define listner actionlistener taskperformer = new actionlistener() { public void actionperformed(actionevent evt) { //...perform task... system.out.println("reading info."); try { class.forname(driver); try { conn = drivermanager.getconnection(url+db,"root","pass"); statement st = (statement) conn.createstatement(); string sql = ""; st.executeupdate(sql); conn.close(); } catch (sqlexception s) { s.printstacktrace(); joptionpane.showmessagedialog(null, "error: please try again!"); } }...

linux - How to find history of shell commands since machine was created? -

i created ubuntu virtualbox machine couple weeks ago , have been working on projects off , on in since then. now find syntax of commands typed in terminal week ago, have opened , closed terminal window , restarted machine numerous times. how can history command go first command typed after created machine, or there place commands stored in ubuntu? 1) size of history file governed environment variable histsize. default 500 lines on systems. 2) can set $histsize in ~/.bashrc (or other) initialization file. 3) can check current history typing "history". 4) can learn more command , various options typing "man history". here's article on subject: http://blog.macromates.com/2008/working-with-history-in-bash/

asp.net mvc - The error of can not find View in Ajax form -

i ask similar question here so add oncomplete functions , id ajax forms, , there is: this view: @foreach(var item in model) { <tr id="tr@(item.id)"> @{html.renderpartial("_phonerow", item);} </tr> } _phonerow : @model phonemodel @using(ajax.beginform("editphone", new { id = model.id }, new ajaxoptions { updatetargetid = "tr" + model.id, oncomplete = "oncompleteeditphone" }, new { id = "editajaxform" + model.id})) { <td>@html.displayfor(modelitem => model.phonenumber)</td> <td>@html.displayfor(modelitem => model.phonekind)</td> <td><input type="submit" value="edit" class="calleditphone" id="edit@(model.id)" /></td> } controller: public actionresult editphone(long id) { //get model id return partialview("_editphonerow", model); } public actionresult savephone(phonemodel model) { //save phone, , updatet model ret...

php - How do I return the variable from a function? -

i trying return variable function , print out. displaying unexpected t_string right now.... can help? function reg_word($i){ $reg_word = "/[^a-za-z0-9 ]/"; $i = preg_replace($reg_word, '', $i); } $suggestion = function reg_word($_post['suggestions']); print_r($suggestion); function reg_word($i){ $reg_word = "/[^a-za-z0-9 ]/"; return preg_replace($reg_word, '', $i); } $suggestion = reg_word($_post['suggestions']); print_r($suggestion); you had function keyword before reg_word($_post['suggestions']); - don't need it. need use return keyword return function.

simplexml - "String could not be parsed as XML" php error -

i keep getting error when try create new instance of simplexmlelement . i checked xml syntax manually , online tools, , copy/pasted example xml file php.net , i̢۪m still getting error. my code: include 'example.php'; $namevalues= new simplexmlelement($xmlstr); the example.php: <?php $xmlstr = <<<xml <?xml version='1.0' standalone='yes'?> <movies> <movie> <title>php: behind parser</title> <characters> <character> <name>ms. coder</name> <actor>onlivia actora</actor> </character> <character> <name>mr. coder</name> <actor>el act&#211;r</actor> </character> </characters> <plot> so, language. it's like, programming language. or scripting language? revealed in thrilling horror spoof of documentary. </plot> <great-lines> <line>php solves web problems</line> </great-lines> <rating type="th...

java - Iterator null collection -

it's quite common have check null before iterate when not sure collection reference null or not. sample: collection<object> collection = ... ... if(collection != null)//troublesome for(object o : collection) of course, know empty collection better null, in cases client code cannot control nullable collection other modules (for instance, return value 3rd party code). wrote utility method: public static <t> iterable<t> nullableiterable(iterable<t> it){ return != null ? : collections.<t>emptyset(); } in client code, no need check null more: for(object o : nullableiterable(collection)) ... do think nullableiterable() reasonable? advice? concern? thanks! that looks good. too. developers disagree kind of defensive programming. imagine have workflow or class not supposed return null . means getting null bug code hide turn null empty collection , bug never surface. if example writing apis not support null collections should avoid this. if clien...

objective c - itemWithNormalSprite with block on cocos2d for ios -

i'm trying create menuitem move gameplay using block , not selector (working on cocos2d ios v2.0) ccmenuitemsprite *nextlevelmi = [ccmenuitemsprite itemwithnormalsprite:playspr selectedsprite:playspr2 block:^(id sender)block]; can give me example such use? 10x, shefy here's example ccmenuitemlabel. apart other parameters it's no different ccmenuitemsprite usage. assume want see how use block. ccmenuitem* item = [ccmenuitemlabel itemwithlabel:label block:^(id sender) { ccscene* scene = [pixelperfecttouchscene node]; [returntomainmenunode returnnodewithparent:scene]; [[ccdirector shareddirector] replacescene:scene]; }]; more examples here , in mainmenuscene , returntomainmenunode example.

iphone - .caf file length differ ,even duration is same -

i have .wav sound file duration 5sec audio channel 2 , total bit rate 1411200. converting file .caf format via command on terminal. after file conversion give following info audio duration again same ( 5 sec), audio channel 1 , total bit rate 705600. now .caf file keeps inside nsbundle. need recording same duration audio file , compare pre-recorded file. when ever nslog both(recorded , pre-recorded) sound nsdata length ,it gives large byte difference(approx. double). i not understand why happen ,even both sound .caf file same duration. please me. in adv. thanks sudesh it depends on following factors of core audio format specification struct cafaudioformat { float64 msamplerate; uint32 mformatid; uint32 mformatflags; uint32 mbytesperpacket; uint32 mframesperpacket; uint32 mchannelsperframe; uint32 mbitsperchannel; }; also check this states depending on above factor caf file length changes

c# - Castle Windsor Register by Convention - how to register generic Repository based on Entity? -

this should general problem, i've searched couldn't found solution yet, if dupe, please point me appropriate link. so, have generic repository support several entites, moment register bellow: public class expensiveserviceinstaller : iwindsorinstaller { public void install(iwindsorcontainer container, iconfigurationstore store) { register<entitya>(container); register<entityb>(container); //etc etc //when there new 1 should register manually } void register<t>(iwindsorcontainer container) t : entity { container.register(component.for<irepository<t>>() .implementedby<repository<t>>() .lifestyle.transient); } } note: repository located on repositories namespace entities located on entities namespace, including entity baseclass of entities it working fine, think should better way, more automatic way using registration convention, when add new entity on project, windsor automatically recognize it, , register repository it. , 1 more...

sql server 2008 - SQL Query Error: SQLDMO -

the following sql query works fine on sql server 2005, on sql server 2008, throws error: sp_security error: unable create sqldmo server object sql query: declare @object int declare @hr int declare @hack smallint declare @return varchar(255) declare @results nvarchar(255) declare @server sysname declare @login sysname declare @tsql varchar(1500) set @server = 'yogesh\sqlexpress' exec @hr = sp_oacreate 'sqldmo.sqlserver', @object out if @hr < 0 begin raiserror('sp_security error: unable create sqldmo server object', 0, 1) return end exec @hr = sp_oasetproperty @object,'loginsecure', 'false' if @hr < 0 begin raiserror('sp_security error: unable set loginsecure', 0, 1) goto exitproc end print ' security audit server : ' + @server set @tsql = 'declare login_cursor cursor select loginname master.dbo.syslogins order loginname' exec (@tsql) open login_cursor fetch next login_cursor @login while @@fetch_status = 0 begi...

python - Scrapy retrieves text encoding incorrectly, hebrew as \u0d5 etc -

first time working stuff. checked out other sof questions internalization / text encoding. i'm doing scrapy tutorial, when got stuck @ part: extracting data , when extract data, text instead of hebrew displayed series of \uxxxx. it's possible check out scraping this page example; scrapy shell http://israblog.nana10.co.il/blogread.asp?blog=167524&blogcode=13348970 hxs.select('//h2[@class="title"]/text()').extract()[0] this retrieve u'\u05de\u05d9 \u05d0\u05e0\u05e1 \u05e4\u05d5\u05d8\u05e0\u05e6\u05d9\u05d0\u05dc\u05d9?' (unrelated:) if try print in console, get: traceback (most recent call last): file "<stdin>", line 1, in <module> file "c:\python27\lib\encodings\cp437.py", line 12, in encode return codecs.charmap_encode(input,errors,encoding_map) unicodeencodeerror: 'charmap' codec can't encode characters in position 0-1: cha racter maps <undefined> tried setting encoding through settings,...

python - Heroku: "directory exists" error after changing requirements.txt -

for 1 of libraries use, i'm trying switch mercurial repository git . unfortunately when tried push project new requirements.txt file, this: obtaining django-storages git+https://github.com/richleland/django-storages/#egg=django_storages (from -r requirements.txt (line 2)) directory /tmp/build_3lujzy9ddaetm/.heroku/src/django-storages exists, , not git clone. plan install git repository https://github.com/richleland/django-storages/ do? (i)gnore, (w)ipe, (b)ackup exception: traceback (most recent call last): ... eoferror: eof when reading line forcing push -f ends same message. how make work? it fixed heroku team pushing new python buildpack, using wipe default kind of conflict.

php - mysqli bind_param does not set $stmt->error or $stmt->errno -

according php manual can retrieve errors in prepared statement method interrogating $stmt->error , $stmt->errno bind_param method never seems set these on error, can else confirm this? or tell me missing please? for example: echo "start\n"; $db = new mysqli('localhost','test','xxxxxx','test'); $val = 1; $st = $db->prepare('insert tbltest set field1=?'); if($st == false) { printf("prepare: %s %d\n",$db->error,$st->errno); } $rs = $st->bind_param('is', $val); if($rs == false) { printf("bind_param: %s %d\n",$st->error,$st->errno); } $rs = $st->execute(); if($rs == false) { printf("execute: %s %d\n",$st->error,$st->errno); } $rs = $st->close(); if($rs == false) { printf("close: %s %d\n",$st->error,$st->errno); } echo "finish\n"; running above command line displays: start php warning: mysqli_stmt::bind_param(): number of elements in type ...

iphone - OCR like Auto Cheat application -

i intending write simple ocr engine iphone "auto cheat" application scans game board of "words friends". how should go doing it? there source codes available me use , alter according need? newbie ocr thingy. pls help. thanks you need check out opencv iphone . question: tutorial iphone opencv on shape recognising , has links out. keep in mind if have never worked opencv before not easy project start with. luck!

javascript - How to make Twitter Streaming APIs work with jsOAuth? -

as has been noted in answer prior question: twitter apis : update working, filter not .. filter api streaming api: https://dev.twitter.com/docs/streaming-apis i make jsoauth work these streaming apis: https://github.com/bytespider/jsoauth it works rest apis, , if has made (or knows how make) work streaming apis, please enlighten me! thanks! jsoauth not support streaming api, confirmed own author: https://github.com/bytespider/jsoauth/issues/29#issuecomment-6841882 looks have find alternative till next release.

ruby on rails 3.1 - Some assets not displaying on Heroku -

i've added new images app , display fine locally, not in production on heroku. css reference generated correct: background-image: url("glyphicons-halflings-white.png") that links http://www.photoramblr.com/assets/glyphicons-halflings-white.png there's no image there, other images i've uploaded in past sitting there under /assets/... instance this one . interestingly, if take long string of numbers out, leaving original filename, image blank... asset precompiling seemed work fine when deploying, , i've tried running asset:precompile manually on server, still no image. any thoughts? update: btw, here's @ config/application.rb : if defined?(bundler) # if precompile assets before deploying production, use line # bundler.require *rails.groups(:assets => %w(development test)) # if want assets lazily compiled in production, use line bundler.require(:default, :assets, rails.env) end module photorambler class application < rails::application # enable ...

Android crop Image -

i using code in this tutorial crop image intent intent = new intent(intent.action_get_content, null); intent.settype("image/*"); intent.putextra("crop", "true"); intent.putextra("aspectx", aspectx); intent.putextra("aspecty", aspecty); intent.putextra("outputx", outputx); intent.putextra("outputy", outputy); intent.putextra("scale", scale); intent.putextra("return-data", return_data); intent.putextra(mediastore.extra_output, gettempuri()); intent.putextra("outputformat", bitmap.compressformat.jpeg.tostring()); but want modify triangle ( used determine area cropped ) aspect ratio x axis longer y axis the com.android.camera.action.crop part of internal api not guaranteed supported android devices (same action_get_content mime type image/* . you have implement own crop activity if want supported devices. @ least should implement sort of fallback behavior if device not support int...

javascript - how to get more that +10/11 LatLng values from markers -

i have array localizations ("street, city, postalcode, province, country"). want have string lat , lng values each localization, ("#lat.value|lng.value#lat2.value|lng2.value.." etc). use google api geocoder. geocoder has annoying limit 10~11 localizations once. how can 100 lat&lng values 100 localization? tried sleep() funcion, doesn't work. function in js. function sleep(time){ time = time * 1000; var start = (new date()).gettime(); while(true){ alarm = (new date()).gettime(); if(alarm - start > time){ break; } } } (..) var mystring = ""; var address = <%=testing %> var arrayaddress = address.split("%"); (var = 0; < arrayaddress.length-1; i++) { sleep(0); geocoder = new google.maps.geocoder(); geocoder.geocode( { 'address': arrayaddress[i]}, function(results, status) { if (status == google.maps.geocoderstatus.ok) { map.setcenter(results[0].geometry.location); var marker = new google.maps.marker({ map: map, position...

actionscript 3 - Is Event TIMER always dispatched before TIMER_COMPLETE? -

is flash.utils.timer object's event timer dispatched before timer_complete? during 2nd event, nullifying stuff required during 1st event; order of prime importance. checked docs , there no guarantee dispatching order. in tests i've done seems case, don't want distribute publicly software without confirming first. you can avoid problem using timerevent.timer only: private function ontimer(event:timerevent) { // ... if (timer.currentcount == timer.repeatcount) { // timer complete } }

lwuit - Codename one builds failing -

i trying port lwuit app codenameone . i have used json package in application. (org.json.me). package part of json jar , contains classes manipulate json files. the application working fine when used make j2me builds lwuit. in codename 1 emulator also, application working without issues. when i, try send j2me build server right clicking project , selecting 'send j2me build', application's build process crashes warnings. executing: javac -source 1.2 -target 1.2 -classpath c:\users\shai\appdata\local\temp\build925171746515355215xxx\tmpclasses;c:\users\shai\desktop\j2me\midpapis.jar -d c:\users\shai\appdata\local\temp\build925171746515355215xxx\tmpclasses c:\users\shai\appdata\local\temp\build925171746515355215xxx\tmpsrc\grestub.java executing: java -jar c:\users\shai\desktop\j2me\proguard.jar -injars . -libraryjars c:\users\shai\desktop\j2me\midpapis.jar -outjars c:\users\shai\appdata\local\temp\build925171746515355215xxx\result\gre.jar -target 1.3 -keep public class **...

css - layout problems with site -

i have problem site. when resize window stays still , doesn't move, window crosses on everything. here images epxlain bit better.. hopefully. this site in normal window - http://imageshack.us/photo/my-images/407/problem2a.jpg/ and when resized - http://imageshack.us/photo/my-images/696/problemim.jpg/ can tell me problem is? layout work website - http://www.thisoldbear.com/ next time, please add html , css code question makes easier , you'll more accurate answers. by looking @ pics feeling you've added left side padding/margin (150px something?) try , center content, when should have added container div(s) margin: 0 auto; this center content , keep centered when resize window update html <div id="container"> <header> <div id="logo"></div> <nav> <a href="#">home</a> <a href="#">about</a> </nav> </header> </div> <div class="content"> .....