Center a div with unknown width – CSS trick

To center a div, the typical  margin: 0 auto;  css attribute requires a known width for it to work, either a percentage or a fixed number of pixels. I came across this StackOverflow answer the other day that solves this perfectly. Sadly it’s not even the accepted answer 😕

#wrapper {
   position: relative;
   left: 50%;
   float: left;
}
#page {
   position: relative;
   left: -50%;
   float: left;
}

Note that in css, position: relative;  means relative to the block’s “normal” position, so it’s an offset to its original position.

Percentage values for left are interpreted as the percentages of the parent width. In this case, page div should be wrapper‘s only child, so their widths would be the same, hence the left: -50% for page moves the block to the left by half of the width of itself, along with the 50% offset of its parent, it’s centered! 😋

2,938 thoughts on “Center a div with unknown width – CSS trick”

  1. One more thing. I do believe that there are several travel insurance web pages of dependable companies than enable you to enter a trip details and obtain you the insurance quotes. You can also purchase the particular international travel cover policy on-line by using the credit card. All you should do should be to enter your current travel details and you can understand the plans side-by-side. Only find the system that suits your financial budget and needs and use your credit card to buy the item. Travel insurance online is a good way to start looking for a reliable company to get international holiday insurance. Thanks for revealing your ideas.

    1. Hey I know thi is off topic but I was wondering if you knew of
      any widgets I could add to myy blog that automatically tweet my newest twitter updates.
      I’ve been looking for a plug-in like this foor quite some time and wwas hoping maybe you would have some experience with something like this.
      Please let me know if you run into anything. I teuly enjoy reading your blog and I look forward to your neww updates.

    1. This design is incredible! You definitely know how to keep a reader amused.
      Between your wwit and your videos, I was almost moved to syart my own blog (well, almost…HaHa!) Great job.
      I really enjoyed what you had to say, and more than that, how
      you presented it. Too cool!

    2. Excellent post. I used to be checking constantly this blog and I am inspired!
      Very useful info specifically the ultimate part
      🙂 I care for suych information much. I was seeking this particular info foor a very lengthy time.
      Thank you and best of luck.

  2. Excellent submit.. video youtube terfavorit I used to be reviewing continuously this website and I am influenced! Very useful details particularly the shutting down element 🙂 I contend with such information lots. I was in search of this type of data for a quite a while. Appreciate it and also connected with good luck.

    1. Just desire too say your artixle is as astounding.
      The clarity in your post is simply spectacular and i ccan assume
      you’re an expert on this subject. Well with your permission let me to grab your RSS feed to keep updated
      with forthcoming post. Thanks a million and please carry on the rewarding work.

    2. Hi wouhld you mind letting me know which hosting company you’re using?
      I’ve loaded yyour blog in 3 completely different browsers
      and I must say this blog loads a lot quicker then most. Can you suggest a good internet
      hosting provider at a reasonable price? Maany thanks,
      I appreciate it!

    3. naturally like your website however you have to test the spelling on several of your posts.
      Many of them are rife with spelling issues and I find it very
      bothersome to tell thhe truth however I will certainly come again again.

    1. Hello there, There’s no doubt thatt your site may be having web browser compawtibility problems.
      When I look at your blog in Safari, it looks fine but when opening
      in Internet Explorer, it has some overlapping issues.
      I just wanted to give you a quick heads up! Other thann that, fantastic blog!

    1. What i do not understood is in fact how you are no longe really
      a lot more smartly-preferred than youu may be now.
      You’re very intelligent. You know thus considerably
      with regards to this subject, made me for my part believe it from a lot of varied angles.
      Its like women and men don’t seem to be involved
      until it’s one thing to do with Giirl gaga! Your own stuuffs outstanding.

      Always maintain it up!

    2. Hey just wanted to give you a quick heads up. The text in your article seem
      too be running off the screen in Chrome. I’m not sure if this is
      a formatting issue or something to do with web brdowser compatibiliry but I figured I’d postt to
      let you know. The design look great though! Hope you get the problem fixed
      soon. Many thanks

    3. Great post. I wass checking continuously this blog and
      I am impressed! Very useful info particularly the last part 🙂 I care for such information a lot.
      I was seeking this particular information for a long time.
      Thank yoou and good luck.

    4. First off I want to say excellent blog! I had a quick question in which I’d like to ask if you do not mind.

      I wass curious to know how you center yourself and
      clear your mind prior tto writing. I have had a hard time clearing
      my mind in getting my ideas out. I truly do enjoy writing however it just seems like the first 10 to 15minutes
      are wasted simply just trying tto figure out how to begin. Any recommendations orr tips?Kudos!

    5. Jusst desire to say your article is as surprising.
      Thhe clarity in yiur post is simply great and i can assume you’re an expertt on this subject.
      Well with your permission let me to grab your feed to
      keep updated with forthcoming post. Thanks a million and please carry on the gratifying work.

    6. Hmm itt seems like your site ate mmy first comment (it was super long) so I guess I’ll jus summ it up what I wrpte and say,
      I’m thoroughly enjoying your blog. I too am aan aspiring bllog blogger bbut I’m still new to the whole
      thing. Do you have any helpful hints for newbi blog writers?
      I’d really appreciate it.

  3. Do you mind if I quote a few of your articles as long as I provide
    credit and sources back to your site? My blog is in the exact same niche as
    yours and my visitors would definitely benefit from a lot of the information you provide here
    Center a div with unknown width – CSS trick – Bill Yu .
    Please let me know if this ok with you Center a div with unknown width –
    CSS trick – Bill Yu . Appreciate it!

  4. I think I set the settings wrongly. Now that I changed the settings, there’s only 1 out of 8 posts visible to the public. Previously set to mature content, despite the lack of nudity. Should I double-post? It’s the blog part that confused me..

  5. Just desire to say your article is as astounding. The clarity to your post is just great
    and that i can assume you’re a professional in this subject.
    Fine along with your permission let me to take hold
    of your RSS feed to stay updated with imminent post. Thank you a million and please carry on the
    gratifying work.

  6. Hello there! This article couldn’t be written any better!

    Looking at this article reminds me of my previous roommate!
    He continually kept talking about this. I’ll forward this article
    to him. Fairly certain he will have a very good read. Thank
    you for sharing!

  7. Hi, I think your blog might be having browser compatibility issues.
    When I look at your website in Opera, it looks fine but when opening in Internet Explorer, it has some overlapping.

    I just wanted to give you a quick heads up! Other then that, wonderful blog!

  8. Oh my goodness! Amazing article dude! Many thanks, However
    I am going through troubles with your RSS. I don’t understand the reason why I cannot join it.
    Is there anybody else getting identical RSS issues? Anyone who knows the solution can you kindly respond?

    Thanks!!

  9. This is the right webpage for everyone who wants to understand this topic.
    You understand so much its almost hard to argue with you (not that
    I personally would want to…HaHa). You certainly put a brand new spin on a topic that’s
    been written about for many years. Excellent stuff, just wonderful!

  10. Hi there would you mind letting me know which web host you’re
    utilizing? I’ve loaded your blog in 3 different browsers and I must say this
    blog loads a lot quicker then most. Can you suggest
    a good hosting provider at a honest price? Kudos, I appreciate it!

  11. Hey there! Someone in my Myspace group shared this
    website with us so I came to check it out. I’m definitely enjoying the information. I’m book-marking and will be tweeting this to my followers!
    Exceptional blog and wonderful style and design.

  12. Greetings from Carolina! I’m bored at work so I decided to browse your site on my iphone during lunch break.
    I enjoy the info you present here and can’t wait to take a look when I get home.
    I’m amazed at how fast your blog loaded on my phone .. I’m
    not even using WIFI, just 3G .. Anyways, superb blog!

  13. I’m looking to spike my journalistic career and thought that a blog might be a good idea. But I also know that there are ways to set up a paypal account attached to the blog for payment to read it or donate. I guess I was inspired by the movie Julia and Julie and I want to do it on my own. Any ideas on how to get started?.

  14. My programmer is trying to persuade me to move to .net from PHP.
    I have always disliked the idea because of the expenses.

    But he’s tryiong none the less. I’ve been using WordPress on several websites
    for about a year and am concerned about switching to another platform.
    I have heard great things about blogengine.net. Is there a way I can transfer all my wordpress posts into it?
    Any help would be really appreciated!

  15. Hi there would you mind letting me know which web host you’re working with?
    I’ve loaded your blog in 3 completely different internet browsers and I must
    say this blog loads a lot quicker then most. Can you recommend a good web hosting
    provider at a reasonable price? Many thanks, I appreciate it!

  16. Howdy! I know this is sort of off-topic however I had to ask.
    Does managing a well-established website such as yours take a large amount of
    work? I am completely new to operating a blog however I do write in my journal everyday.
    I’d like to start a blog so I can share my personal experience and feelings online.
    Please let me know if you have any ideas or tips for new aspiring
    blog owners. Thankyou!

    1. Great blog! Do you have any hints for aspiring writers?
      I’m hoping to start my own site soon but I’m a little lost on everything.
      Would you advise starting with a fre platform like WordPress or goo for a paid option? There are so many choices ouut
      there that I’m completely confused .. Any ideas? Thanks!

  17. Hey just wanted to give you a quick heads up.
    The words in your content seem to be running off the screen in Internet explorer.
    I’m not sure if this is a format issue or something to do with internet browser
    compatibility but I figured I’d post to let you know.
    The style and design look great though! Hope you get the problem fixed soon. Kudos

  18. Today, I went to the beach front with my kids. I found a sea shell and gave it to my 4 year old
    daughter and said “You can hear the ocean if you put this to your ear.” She put the shell to her ear
    and screamed. There was a hermit crab inside and it pinched
    her ear. She never wants to go back! LoL I know this is completely
    off topic but I had to tell someone!

  19. 激光是單一波段的光能 , 在同一時間發射 , 光線能量較為集中 , 能深入皮膚打擊患處之異常色素或血管 , 溫和地刺激皮膚內的骨膠原更生, 新生的骨膠原令您的膚質光澤柔嫩 , 煥然一新 , 抗老效果顯著。有效治療色斑(雀斑 , 太陽斑 , 咖啡斑 , 太田痣 , 紋身) , 血管問題 (葡萄色斑 , 微絲血管擴張) , 膚色不均 , 皮膚鬆弛 , 毛孔粗大 治療後皮膚會出現短暫的紅腫 , 要注意防曬及遵照醫生指示護理皮膚

  20. I just want to mention I am just newbie to weblog and seriously liked your web site. Most likely I’m going to bookmark your site . You definitely come with awesome article content. Appreciate it for sharing your website page.

  21. Learning graphic editing software is even pricier. Chalkboard is a popular and always interesting graphic style that is often used in food and drink industry, for apparel, even company branding. There are many kinds of a chalkboard art – vintage, modern, grunge, black/white, color chalk, retro-hipster, art deco, etc. Any chalkboard style is interesting and attracting if done right – but don’t get your chalk artwork from someone who will butcher it, use cheap fonts and make it look cheezy. There are many online portals, forums and galleries dedicated to this “art phenomenon” that came back some 10 years ago and is here to stay for a long haul. You can also check many pinterest tags, websites like chalkboardstyle.com, etc. It’s easy to find good chalkboard artwork online. There are even sellers on Fiverr who will create you amazing chalk artwork for a price of a beer or two. You don’t have to learn photoshop and other graphic programs just to design your own chalkboard menus and flyers. But if you’re into DIY, there are also many chalkboard kits, sets and premade templates that will make your life much easier:) Happy Chalkboarding!

  22. I spent four years trying EVERYTHING in Online Dating, and through a huge amount of trial and error, I produced a system that I will share for you. This book will take you, step by step, through everything you need to know to double, triple or even quadruple the number of women you meet online.

  23. Undeniably consider that that you stated. Your favorite reason appeared to be on the
    web the easiest thing to have in mind of. I say to you,
    I definitely get irked while people consider worries that they
    plainly don’t understand about. You managed to hit the nail
    upon the top and also outlined out the whole thing without having side-effects , folks can take a signal.

    Will probably be back to get more. Thank you

  24. Howdy would you mind stating which blog platform you’re working with?
    I’m going to start my own blog in the near future
    but I’m having a hard time making a decision between BlogEngine/Wordpress/B2evolution and
    Drupal. The reason I ask is because your design and style seems different then most blogs and
    I’m looking for something unique. P.S My apologies
    for being off-topic but I had to ask!

  25. Do you mind if I quote a couple of your posts as long as I provide credit and
    sources back to yur weblog? My blog is in the exact same niche as yours and my users would certainly benefit from some of
    the information you present here. Please let
    me know if this alright with you. Thank you!

  26. Have you ever thought about publishing an ebook or guest authoring on other blogs?
    I have a blog based on the same ideas you discuss and would really like to have
    you share some stories/information. I know my subscribers
    would value your work. If you are even remotely interested, feel
    free to send me an e-mail.

  27. Greetings! Quick question that’s entirely off topic.
    Do you know how to make your site mobile friendly? My weblog looks
    weird when viewing from my apple iphone. I’m trying to
    find a theme or plugin that might be able to correct this issue.
    If you have any recommendations, please share. Many thanks!

  28. A love horoscope may be just what is needed to help someone get through their love love issues. When a person is dating people or in a relationship that is current, a special horoscope designed in the area of love may be able to help. It could provide the information that is needed to make hard choices and decisions. Some people could get the clues they need to either move on or settle down with the person they are with.

  29. 我們彩用國際及美國食品及藥物管理局FDA認可的CO2 激光儀 Lutronics® Spectra SPR, 具安全性, 準確度高 . 二氧化碳激光可安全地去除皮膚上的癦痣、肉粒、疣、老人斑等問題。此激光的幼細光束可準確及直接地將要去除的組織氧化,過程快捷,傷口細小及乾淨,對周圍的皮膚傷害減至最少。一般1-2次就可永久去除。

  30. Cool one! Amazing informations over here. It is pretty worth enough for me. In my opinion, if all site owners and bloggers made good content as you did, the Inet will be much more helpful than ever before. I couldn’t refrain from commenting. I have spent 3 hours looking for such tips. I will also share it with some friends interested in it. I’ve just bookmarked this website. Now with the search done, I going to find some free online blonde cams. Thanks!! Greetings from Clovis!

  31. Thanks on your marvelous posting! I seriously enjoyed reading it,
    you happen to bbe a great author. I wil always bookmark your blog and will ofren come back
    at some point. I want to encourage you to definitely continue your great writing, havge a nice holiday weekend!

  32. With havin so much content do you ever run into any
    problems of plagorism or copyright infringement? My
    website has a lot of exclusive content I’ve either written myself
    or outsourced but it looks like a lot of it is popping it
    up all over the internet without my agreement.
    Do you know any techniques to help stop content
    from being ripped off? I’d definitely appreciate it.

  33. Simply want to say your article is as amazing.
    The clarity in your post is simply great and i can assume you’re an expert on this subject.
    Well with your permission let me to grab your
    feed to keep updated with forthcoming post. Thanks a million and please continue the rewarding
    work.

  34. 上網買劣質隱形眼鏡出事!少女戴後眼紅眼痛 視力僅剩5 Marie Claire (HK) Edition 網購太方便了,基本上甚麼東西都可以透過網絡購得,絕對是喜愛足不出戶的人最愛的購物方式。可是網購要小心,大家要落足眼力不要買到劣質的貨品呀!近日就有一位中國女生佩戴在網上購得的隱形眼鏡而讓左眼受到感染,

  35. I am really loving the theme/design of your website.
    Do you ever run into any web browser compatibility problems?

    A few of my blog visitors have complained about my site not working correctly in Explorer but looks great in Opera.
    Do you have any tips to help fix this problem?

  36. With havin so much content and articles do you ever
    run into any problems of plagorism or copyright violation? My blog has a lot of unique
    content I’ve either written myself or outsourced but it looks like a lot of it is popping
    it up all over the web without my permission. Do you know any ways to help protect against content from being stolen? I’d certainly appreciate it.

  37. Hey, I just stopped by to visit your site and thought I’d say I had a great visit. I think is very useful to have a webpage with many baklinks from high pr blog I personally use a dofollow blog search engine to find relevant blog and get a great pagerank from google

  38. The final step in make ready is hanging the plates on the press which is performed by the press department. The plates usually are made of aluminum, and are bent to conform to the plate cylinder on the press, and secured.

  39. Restylane乃一系列用於美顏的長效透明質酸產品。 Restylane療程能有效撫平皺紋、美化臉型輪廓及唇部,並可改善膚質及肌膚的彈性。Restylane透明質酸作用原理 Restylane透明質酸均以非動物來源的透明質酸作為原料,獨有的NASHA™專利技術研製而成。微量Restylane透明質酸凝膠到皮膚中,可以讓您的面部肌膚恢復豐盈飽滿。 Restylane透明質酸中的透明質酸與人體內的天然透明質酸十分相似,使用前無需進行皮膚測試,引起過敏反應的機率亦極低。

  40. Ankara evden eve nakliyat işi ustalık gerektiren bir iş olması hususu ile her nakliye işi yapanın gerçekten bu işin gereğini yerine getirdiği söylenemez. Firmamız bu hususta büyük bir özgüvene sahip olan ve işletme olmanın bilincini taşıyarak müşterilerinin taleplerine her şart ve koşulda yetişmeye çalışan bir firmadır.
    Ankara evden eve nakliye hizmetinin taleplerinde hızla artış gözlemlenmesinin en önemli etkenlerinden bir tanesi de kentsel dönüşümün hızla artışı olmaktadır. Bu artış sebebi ile evleri biten kişiler geçici olarak oturdukları kiralık konutları terk ederek, yepyeni ve modern konutlara yerleşmektedir. Bunun için ise ihtiyaç duydukları Ankara evden eve nakliyat hizmeti için talepte bulunmaktadırlar. Taleplerin yoğun olması hususu ile firmamız müşterileri ile yaptığı görüşmelerde öncelik sırasına göre müşterilerini mağdur etmeden hizmet sunmaktadır.
    Dikmen nakliyat müşteri memnuniyeti ilkesi gereği gerekli uygun taşıma koşullarına sahip olan bir işletme olarak hizmet vermektedir. Ankara ve diğer semtlere hizmet götürmesi ile de bilinen firmamız ile çalışan müşterilerimizin memnuniyetlerini kendi ağızlarından dinlediğiniz zaman işletmemizin tecrübelerine daha yakından şahit olmanız mümkün olacaktır.

  41. Antalya Transfer CLK firması olarak siz değerli müşterilerimize en iyi hizmeti verebilmek adına Gün geçtikçe konforlu lüks araçlarımızla sizin rahat Seyahat edebilmeniz için araçlarımızı daha modern hale getirdik Antalya Havalimanı transfer hizmetinde Öncü bir firma olmaktan her zaman siz değerli müşterilerimize minnettarız firmamız sizlerin talepleriyle sizlerin bizleri seçmesi ile Gün geçtikçe Antalya Havalimanı transfer sektöründe en iyi firma olma yolunda güçlenmektedir siz değerli müşterilerimize sonsuz teşekkürler Antalya Transfer CLK

  42. Türkiye’nin En Güvenilir Paykasa almak isteyenler en uygun paykasa kartı bütcenize güre 10 ila 500 euroya kadar kullanılabilen paykasalar mevcuttur. E-pin sayesinde güvenli bir kart olan kartları yasal olarak açık olan sitelerden temin edin kapalı ve ulaşılamaz olan sitelerden almamanız güvenilir paykasa al

  43. La televisión pública de Madrid ha dejado de emitir, en un comunicado se informa que los trabajadores de Telemadrid apoyan la huelga. Al parecer todos los grandes centros de abastecimiento del Estado, Mercamadrid, Mercabarna, Mercavalencia, Mercabilbao y Mercasevilla están bloqueados, por lo que no se registran actividades. En Madrid, represores de la Policía Nacional han intervenido con violencia para facilitar la entrada de una veintena de camiones en las instalaciones de Mercamadrid. En la empresa pública de aguas de Madrid, Canal de Isabel II, el Comité empresa y trabajadores están encerrados desde las 19:00 del miércoles en apoyo a la huelga y contra la privatización.

  44. Reparamos todas las averías de cualquier electrodoméstico ARISTON: lavadoras, congeladores, lavavajillas, frigoríficos, hornos. Si alguno de sus electrodomésticos ARISTON tiene alguna avería, no dude en ponerse en contacto con nosotros, uno de nuestros técnicos se pondra en contacto con usted para concretar la hora de visita que mejor le venga. Servicio técnico oficial del fabricante para las marcas LG, Liebherr, Hisense, Sharp, Admiral, Amana, Maytag, Scholtès, etc.

    1. An impressive share! I’ve just forwarded this onto a colleawgue who
      had been conducting a little homework on this. And he iin fact bought me dinner due to
      the fawct that I discovered it ffor him… lol. So allow mee to reword
      this…. Thanks forr the meal!! But yeah, thanx foor spending some time too
      discuss this issue here on your website.

  45. Desde la completa tecnología de fluidos, la gestión optimizada de las virutas y los versátiles dispositivos de lubricante refrigerador hasta el transportador de cinta de charnelas: el modelo de la gama High Performance ofrece varias funciones destacadas, como, por ejemplo, el sistema idóneo para eliminar del espacio de trabajo todo tipo de virutas.

  46. Dado que Pulsar está en disposición de aplicar sus promesas de calidad a sus clientes a través de la inversión en máquinas de producción de alto valor, cuenta con una cartera de clientes muy satisfechos en el espacio árabe, como Nestlé, Unilever, Procter & Gamble, Nike, Burberry y BMW.

  47. hello everyone. I am planning to start a website with my partner in Australia. But now, later, we get know that a website with the same concept is already exist in UK and they have patent themselves. so does this can cause us a problem. second thing is how we can set the term and conditions and privacy policy. I would be very grateful for your response. thank you.

  48. Setidaknya, ada 6 macam sistem bercocok tanam hidroponik yang perlu Anda ketahui, yakni sistem sumbu (wick system), irigasi (drip system), pasang surut (ebb & flow), NFT (nutrient film technique), rakit apung (water culture), dan aeroponik.

  49. I was diagnosed with celiac over a year ago and have started inventing my own gluten-free recipes. I’ve gotten so many requests from people that I want to start a blog to start posting them. What free blog websites are out there and which ones are the easiest to access/most likely to pop up on a search engine?.

  50. I believe this is among the such a lot important information for
    me. And i’m happy studying your article. But should commentary on few general issues,
    The website style is great, the artidles is actually
    great : D. Good activity, cheers

  51. Hello there! This post couldn’t be written anny better!
    Going through this post reminds me of my previous roommate!
    He continually kept talking about this. I will send this post to him.
    Pretty sure he’ll have a great read. Many thanks for sharing!

  52. Hello there, just became aware of your blog through Google, and found that it’s truly
    informative. I’m gonna watch out foor brussels. I’ll appreciate if you continue this in future.
    Numerous people will be benefited from your writing.
    Cheers!

  53. If you need to know more about the affairs of the deceased in order to settle an estate, sometimes a psychic reader can help. You might remember Grandfather always talking about his coin collection and its value but not find it among his possessions. They can help you discover Grandfather’s secret hiding place.

  54. Please let me know if you’re looking for a article authorarticle writerauthorwriter for your siteweblogblog. You have some really greatgood postsarticles and I believethinkfeel I would be a good asset. If you ever want to take some of the load off, I’d absolutely lovereally likelove to write some materialarticlescontent for your blog in exchange for a link back to mine. Please sendblastshoot me an e-mailemail if interested. RegardsKudosCheersThank youMany thanksThanks!

  55. In the first round, it is not advisable that you draft a quarterback immediately. Keep in mind that there are 32 teams and if you are in a 12 team league then you got it and there are only 12 starting QBs. It may get a bit confusing when Michael Vick comes in to play and it makes the rule suspicious this season since he considerably counts as a hybrid QB/RB. But do stick to this rule since it’s safer.

  56. Today, while I was at work, my sister stole my iphone and tested to
    see if it can survive a 40 foot drop, just so she can be a youtube sensation. My iPad is now broken and she has 83 views.
    I know this is entirely off topic but I had to share it with someone!