T O P

How do I make the inner div to be vertically centered inside the bigger div?

How do I make the inner div to be vertically centered inside the bigger div?

Wasseemen

div { display: flex; align-items: center; // Vertical Alignment } This should do the trick :).


nowtayneicangetinto

Honestly, if it wasn't for flexbox I'd be so shit at front end


enserioamigo

Display flex everything.


zen-bot

Every once in a while, grid is better.


LeeLooTheWoofus

I typically use grid for macro layouts and flex for micro layouts. In other words - if it is a page layout, grid. If it is a component layout inside that page, flex.


Darkmaster85845

Yep that's the way to go.


Candyvanmanstan

I wouldn't dare use grid for whole page layouts yet, there's only like 4 years backward support? Edit: feel free to enlighten me why I'm wrong, i would love to use it.


FryHigh

I agree. For professional development Browser compability is a must and I think many people do Not Update their Browsers let alone their operating System.


Aswole

I'm a bit odd.. if there is a knowable # of children, regardless of complexity, I use grid. I only use flex for dynamic lists of elements. I just prefer how much easier it is to refactor/move elements around with grid when design specs change in the future, especially when defining grid-areas with labels. Also nice for responsive design as you can set breakpoints that completely change the grid-template-areas definition. Accessibility is a bit tricky though because it is easy to move elements in a way that betrays their position in the document.


Admin-12

I’m learning and this unlocked a new level for me. Thanks!


MLV07

Agreed.


noXi0uz

this!


TopsyKrett3

I just converted my page layout from flex to grid, so glad this validates my decision!


ant1g3n

Is it recommended or a best practice to use Grid to structure our entire web page or certain parts/sections of the page?


FortyPercentTitanium

It's probably what most people do, but it's really up to you. Practice will help you figure out which is best for each situation.


ant1g3n

I've seen other devs create 12 column grids and then align/span individual boxes/sections across this 12 column grids. I don't know if that's necessary to do, I mean I still don't get it why we need a 12 column grid to structure an entire web page.


landisdesign

This comes from print design, where elements were laid out according to the number of columns they took. Bootstrap made this a very common way of doing things. It can help provide consistency across multiple unconnected rows, but can also be overkill.


ant1g3n

Thanks!


ycbx

There is a performance limit for how many grids render on a page for some browsers, not sure if that is a slated fix, but something to be weary of on complex sites and using it a lot


MaggoLive

As long as flex-gap is not standard yet I'll prefer grid any day


Padrone__56

Only for doing actual grids. People shouldn't use grid for rows of items


YogurtCode

Grid-template-area is super nice foraking an entire layout.


big_red__man

I agree but with how the clients and designers work (and all of the changes that come with it) I use a 12 column flexbox solution for all of my sections. If a section consists of tiles then grid is great for that.


dr_hewitt

You can use grid for that too. I'd argue that grid is far more suited for a macro layout like a 12 column grid than a flexbox solution


big_red__man

It depends on the design and how that design might change. The rigidity of grid is great for many applications but the non-rigidity of flexbox is very welcome at times.


morete

Eh, "actual grids" is a bit meaningless, if you get the results you want with grid, use grid


codicate

I mostly use grid with place-items center


knightofren_

Tbh they solve different problems. They work best when using them together. Grid for setting out the overall page/content layout, flex for setting up items in individual grid containers.


SarahC

I KNEW TABLES WERE AMAZING. Seriously - 9 section images for scaling, headers, and side bars. Footers. Tables have got you covered, and worked on every browser since 1993. Even Emails in Outlook! Some pages I've seen converted from tables to DIV layouts, and .... no benefit was seen. They scaled like the table version, but took longer to layout to get all the individual DIV's playing with each other. Sure "Tabular data goes in tables" - but only if you're thinking in long columns. They're so much more flexible than that. And NAMED CSS CELLS for the CSS tables? HEAVEN! Just re-define the areas - header/footer/sidebar/content, with header/content. and you've got responsive content in a couple of lines of CSS. -retires happily-


UnusualMuffin1242

Wanted to upvote but... you know why I didn't XD


Web-Dude

>grid is better You said the words. Let the holy war begin again!


iWritePythonLikeThis

Flex? You mean float for preschoolers? (joking, love flexbox and grid)


shadow_burn

`* { display: flex; }`


squirrelwithnut

Don't do this with Grid.


Capital_Bid7389

TIL there are some criminals who don't use flexbox


nowtayneicangetinto

I work with some old school devs. One is very resistant to change. When I showed him flexbox, I imagine it's like what showing modern technology to uncontacted tribes is like.


torn-ainbow

Old school dev here, Flexbox solves all sorts of problems. It good.


YogurtCode

But we have to use tables and float to flex on the young ones.


torn-ainbow

fuck tables. double fuck float.


tousonuk

I feel a font-size:0 coming on to get the nasty spacing demons away


troop99

Hahaha, yeah the floats. Thank God we don't need them anymore!


mycockstinks

Dev for 20 years. There's a lot of new-fangled things I don't like but flexbox is not one of them. Flex all the things.


nowtayneicangetinto

Yeah I agree, I didn't realize the full power of flexbox until I did some react native work, where literally all of the styling is flexbox. If you haven't done CSS grid yet I highly recommend it. It's just flex box in two dimensions with a ton of customizations


mycockstinks

Yeah, use grid occasionally. Usually when I want to do something where I would have used rowspan="2" back in the tables days.


omgdracula

I showed our lead dev on our team Sass and he said he didn't see the benefit of it over regular plain old CSS. So then I showed him how mixins work and how you can change a bunch of elements with just one line of css. Along with nesting and the other great things Sass does. Blew his mind. Haven't kept up with CSS itself so not sure if any features from Sass have finally made it to spec.


ant1g3n

Sass Variables -> CSS custom properties.


omgdracula

Ah good to know! Now CSS just needs nesting!


versaceblues

Just wait until some junior dev under you shows you emotion or styled-components. Pretty much made me stop using SASS


omgdracula

Oddly where I work I am one of the youngest devs on the team hah. The other devs are older than me. I am going to look into both of these though.


versaceblues

If you are using ReactJS or some other view framework CSS-in-JS is actually an amazing invention. If you are going frameworkless then SASS is probably still the best.


TehTriangle

I went from thinking 'why the hell would I need something like Styled-components' to now having used it for so long, I've almost forgotten vanilla CSS/SASS, it's embarrassing.


dreadlockdave

Unless you need ie support css has custom properties now which replaces variables and nesting is supposed to be coming soon. Unaware of anything to replace mixins but regular CSS is getting better all the time. I still use sass for now but I think there will be a day where it isn't needed. CSS nesting spec: https://drafts.csswg.org/css-nesting/


omgdracula

Unfortunately due to me being at a large corporation we have to support ie11. RIP. Glad to hear nesting is coming. One of the best things.


everything_in_sync

Do you make all CSS work for all browsers or do you use modern CSS for the browsers that support it and then detect Ie and write different markup?


omgdracula

I have my Sass compliling run an autoprefixer for anything that needs it for IE11 so I only load one stylesheet instead of needing to detect IE. Only for the business areas that need IE11 though.


montrayjak

Still, it would be great to just code in native CSS, then transpile/minify (pack) for all browsers after. It's essentially what I'm doing with JS these days.


dreadlockdave

I feel your pain, two of the websites I work on for work need ie support, sass and autoprefixer help a lot but even adding fallbacks can't fix that pile of ****


omgdracula

IE11 is luckily gone "soon". But then safari remains. WE CANT WIN!


ur_comment_is_a_song

Safari is often worse than IE tbh


tousonuk

I discovered the bootstrap utilities generator today, Holy shit what a great use of Sass. Extend any bootstrap directive to be responsive and the utility generator creates all the breakpoint equivalents. WALLOP!


Codemonkey1987

Done that one. Me wondering why they don't use github but instead have file-1 file-2 file-3 file-4 file-5 etc. Hmm I dunno sounds unnecessarily complex and insecure. We like our method.


stfcfanhazz

Wow quit that place


Codemonkey1987

I did!


enserioamigo

Ctrl+C Ctrl+V is the best backup method. /s


enserioamigo

My first interaction with HTML was when frames were a thing. I’m assuming they use frames and tables a lot?


PGDesign

Pretty sure frames are deprecated now - though that doesn't stop people who really want to stick to old versions


the9trances

Even silverback front end devs don't use tables for positioning anymore. Two of the old habits are auto margins and line-height.


imnos

Bet they love some good ol' auto margins.. margin-left: auto margin-right: auto


TehTriangle

Can be useful in some cases still.


skylla05

I knew about Flexbox but just kept using what I knew because I just convinced myself I was too busy to take the time. When I had to work on something another person did with flexbox and had to understand it, man, changed my life. I can't imagine not using it now.


crimson117

Last I remember you had to set the margins equal in order to center. Is that not a thing anymore? Haven't done any significant front end since 2013.


b11x

Iirc that only works when heights are defined for everything in the DOM tree? And a set height on the element? Otherwise it just sits there confused as to where the vertical center is. Something like that, my memory is bad


IAmRules

I come from a time where everything was tables, when DIV's came out we were like "WHAATTTT" edit: brain fart


[deleted]

[удалено]


IAmRules

yup, thanks for the catch


TotallyNotACatReally

I come from the email world where everything still is tables. (Please send help.)


hexcowboy

You couldn’t imagine the kind of things we did before flexbox


Raze321

Floating wasn't too bad. .row:after { clear: both; } .column { float: left; width: 33.33%; } Boom, three column layout, probably.


bailz

These kids haven't earned their spots at the big boy html table.


DragoonDM

> html table _Angry hissing_


Smaktat

No one remembers vertical alignment anymore. I still have no idea when and when not that would work.


jamesianm

Pretty much never. I used to always resort to position:relative; top:50%; transform:translateY(-50%);


editor_of_the_beast

Flexbox honestly saved frontend webdev, it’s the only way to do certain things with any amount of sense.


StrawberryEiri

The old way would probably be `display: inline-block; vertical-align: middle;` on all children. Or you could go with `display: table-row;` and `display: table-cell;`... I THINK that would work?


godstabber

Want to know the old school way? All child divs should be display inline-block and vertical-align middle.


ManiacsThriftJewels

Yeaaaah, that.... Doesn't work as well as you'd hope....


[deleted]

I can’t imagine doing that whole -50%, -50% to Center things now that I’m used to flexbox


jseego

They way we used to do this back in the day was either adjust the margin on the vertically centered item and pray for the best, or use a table-cell spoof hack, or bastardize line heights, or use relative positioning, or set the position via javascript if it needs to resize at all. None were really good options. I actually used to get in fights with people, like backend devs who were telling me, oh that can't be right, I'm sure there's a way to vertically center elements in css. I was like, um I'm the UI dev and I'm telling you there's not. Oh, I'm sure there must be a way. And I'm sending them articles and they don't want to believe it. Smh.


Norlad_7

Amen


sirephrem

we'd all be


william_103ec

Do you have all the syntax at the top of your head? Or still using some sort of cheat sheet?


code_matter

I mean you could do it multiple ways. If you want, look into absolute/relative positions! For instance, if you put the main div as position: relative, you can place the items inside relative to it. So you could do this on the second div to center it vertically : position: absolute top: 50% transform: translate(-50%) You'd still have to position it from left to right, but it would be vertically aligned! To center the div completely within a relative div do this: position: absolute top: 50% left: 50% transform: translate(-50%,-50%) Edit: absolute not relative Edit2: why the fuck am i getting downvoted? Does it work? Does it get the job done? Yes.. im not saying its the ultimate way.. wtf haha


SupaSlide

I know this is just an example, but flexbox actually has slightly better browser support than the `transform` property, which was kind of surprising to me for some reason.


Smaktat

Very simply, just because it works doesn't mean we want to see it, especially to someone newer.


JourneyToJah

Second snippet should be position: absolute; As well. While this works, it’s not the ideal way to do it.


daftv4der

I'm so glad I got good at FE before it. I'd have been so lazy otherwise.


ant1g3n

Same here 😂


Cr4nics

Also add a class to the outer div and use that in the css to prevent also centering the contents of the inner div


Wasseemen

Very true! I would recommend naming everything that requires styling rather than generalizing as it's better to manage and overall looks cleaner.


kevscript

> align-items: center; // Vertical Alignment Just keep in mind `align-items` alignement isn't inherently vertical. Its base on the `flex-direction` value, which happens to be `row` by default. `flex-direction = row` ? - `align-items` vertical - `justify-content` horizontal `flex-direction = column` ? - `align-items` horizontal - `justify-content` vertical I kinda wish there was a better naming convention.


fCJ7pbpyTsMpvm

It doesn't matter how often I write this, I will never remember which one is which.


HeinousTugboat

It's like USB. I try it one way, it doesn't work. I try it the other way, it still doesn't work. I try it the first way and it works.


Atulin

Not to mention there's also `align-content` and `justify-items`


human_brain_whore

Hot-reloading to the rescue. Always. It's not even 50/50 whether I'll get it right.


Begj

Shit. This explains so much of my confusion. Thank you


Merhat3

Weird flex but ok


thesilverbeard

This is the correct answer


Whole_Food

Yo happy cake day


tiempo90

Welcome to the world, of "display: flex"


mausisang_dayuhan

FlexBox works better than the old ways, but just in case you were looking for a non-flex way to do this... [CodePen demo](https://codepen.io/mausisang/pen/YzZmqvQ)


zen-bot

Don't forget `flex-direction: row;`


knuppi

`row` is the default, no need to specify


j00stmeister

row is the default of flex-direction so you don't need to explicitly set it.


vcanas

You don’t need to explicitly set it but might be worth mentioning that align-items is not vertical alignment if column is set. It is cross-section alignment and in that case justify-content is what would give vertical alignment Edit: cross-axis


comfort_bot_1962

:D


litaci

Flex-flow: row nowrap


comfort_bot_1962

:D


ice2kewl

Draw it in the middle.


ClassicPart

This is the correct answer. I'm not sure why everyone is talking about HTML elements and CSS when the OP is very clearly using a paper+pencil-based stack. ^^^*ducks*


[deleted]

BOOOOOOOO


alt3r3go99

🏅


DragoonDM

Just toss a bunch of `
`s above it until it looks about right.


blayhem

> back-end Checks out :P


kallakukku2

Nicely spotted


human_brain_whore

Bruh.


zerik100

🗿


carlos_vini

http://howtocenterincss.com/


Norlad_7

As others said (and actually gave the solution), the easiest way to do this is using Flex in your CSS. Flex is not that complicated to grasp. If you're learning CSS and not only looking for this one solution, I'd highly recommend you check out for learning Flex in a somewhat fun way : https://flexboxfroggy.com/ Edit: And later if you want to learn grid, which is another great CSS tool for layouts, check out : https://cssgridgarden.com/


enserioamigo

Also CSS Tricks have the best reference page for it. Always going there when something isn’t working. https://css-tricks.com/snippets/css/a-guide-to-flexbox/


Norlad_7

Ahah, I was just about to edit my answer to include that one :D It's great indeed I sometimes even wish I printed the cheatsheet, but oh well.


The_Dretones

I've been using this guide for years. So helpful.


enserioamigo

And not even a single ad. If it was w3 it’d have at least 20 ads on the page


hannahatl

Flexbox Froggy was so great for me to understand flexbox! [This](https://darekkay.com/flexbox-cheatsheet/) also helped me a lot too!


elgeokareem

Wow thanks for that link


CelticHades

That's good,thanks man.


wasdninja

Flexbox isn't overly complicated to learn but I remember it being confusing and/or frustrating that it assumed control over the child elements and stretched or shrank them as it pleased. It's not an issue anymore so I guess it's just something to get used to.


goobersmooch

I havent fought with css in about 8 years now. I'm happy to see that vertical centering is still haunting people.


krishopper

Not as much as it used to, thanks to flex.


comfort_bot_1962

Nice!


comfort_bot_1962

Hope you do well!


noknockers

The age old question. Devs have been asking this for 20 years.


wasdninja

And for 11 of them flexbox has been the answer.


KaizenCyrus

**CSS** ``` div img { display: inline; } div #slogan { display: inline-block; } ``` **HTML** ```

Text
```


ddoonnaalldd

Guys this is OP posting his code, not someone posting a wrong solution. Don't down vote.


Wasseemen

**HTML**

Text

**CSS** /* Outer DIV */ .wrapper { display: flex; align-items: center; } .inner-wrapper { // Your extra styling for the inner DIV } ​ Please avoid styling using ID for many reasons but mainly in my opinion, if you are to have multiple elements/blocks in your page and would want to apply the same style, it would not work by providing the same ID for both elements (technically it would but that's a different story). Also, I highly recommend wrapping text with a tag rather than just letting it be inside a div as the main purpose of a div is to act as a section. (I have wrapped it with a

tag in the code block :)) ​ Additionally (I promise this is the last point :( ), `display: inline-block` can get outclassed by `display: inline-flex or display: inline-grid` as both of these have much stronger inline layout system and can do the exact same thing but better.


Tarandon

Not to mention duplicating IDs in your mark-up is against WCAG guidelines. It makes the site harder for assistive technologies to understand your site.


hakujoo

div > img, div > div {display: inline-block; vertical-align: middle;}


smegnose

You young whippersnappers and your flexboxes! Back in my day we had to use [all sorts of tricks](https://vanseodesign.com/css/vertical-centering/ "6 Methods For Vertical Centering With CSS - Vanseo Design") to do this, even _tables_ depending on the target browser (cough IE6, cough). Once [this was the "holy grail"](https://alistapart.com/article/holygrail/ "In Search of the Holy Grail – A List Apart").


Tintin_Quarentino

position: relative; top: 50%; transform(translate-y): -50% Something like this? I know *some* combo of position absolute/relative on parent & child element would do the trick, don't remember though but nothing a few trial & errors can't solve.


smegnose

Once upon a time, transform did not exist. When it arrived, it was something used only by developers who loved the latest and greatest, and wowed their clients without caring that a huge portion of the end users would get a broken layout. You could only do something like you wrote with fixed-height elements.


Pwntheon

Well, it would at least have had to be ```transform: translateY(-50%);``` i think


Bandude

I was thinking they same thing, I've moved into back end mainly so I've lost touch on all the new fancy stuff.


smegnose

I do all the ends, and flex is fantastic, though it does have a few quirks. I don't miss the old methods of doing things, or having to tell bosses/clients that their idea is just not practical.


jonwolski

I've been doing this since those days, too. (remember when IE 5.01, 5.5, and 6 existed simultaneously but each with different bugs 😃) This particular one is _really_ easy: `vertical-align: middle`. That's from CSS 1 and works well cross-browser. (The challenge _then_ was that `display: inline-block` didn't come out until CSS 2 and wasn't supported in IE until 7.)


BurnMyFaceOff

Can you rub it out and draw it again but just higher up? might need a ruler but that should do the trick


Tintin_Quarentino

MVP


litaci

Use flex buddy. Search flexbox mdn for more info


KaizenCyrus

If there's something I learned from asking this question, it's that this would be asked again soon eventually.


Septseraph

What they are not telling us, is it has to work for IE7.


relishtheradish

The eternal question of web dev


UnusualMuffin1242

This question never get's old...


jaesung2061

I just came here to comment on the the drawing; it's a work of art.


cronixi4

Spend some time learning flexbox, it is the best thing that could ever happen to the web.


Value_Bluffs

Display flex on all the things! That’s my motto anyway


DonLini

Give the parent div a display of flex use align center. That'll center the children vertically. So that Parent{ Display : flex alignItems: center }


TecJon

I think someone needs to make a website for this. Or an article. Or at least an infographic.


Dan6erbond

There are at least as many videos, websites, articles and graphics for this as this question has been asked for the past 20 years.


LethargyLiving23

The secret ingredient is flex


lost_man_wants_soda

Flex box!!! Woooooo Go play flex box froggy


masteryder

I know you probably just want to align everything to the center, and that you can achieve with display: flex; however, if you only want to center the div with text, here's what you can do using position absolute: https://codepen.io/masteryder/pen/BaWXNxV


ant1g3n

On outer Div set the following properties: .outerDiv { display: flex; align-items: center; }


bubbacorp

Pretty useful resource: http://howtocenterincss.com/


leiu6

You are going to want to set the parent div to be display: flex. Then you can vertical align all the children with align-items: center.


3rdPoliceman

lmao how does this have 170+ comments?!


ur_comment_is_a_song

You just gotta ~flex~ bro


burnblue

People have posted display flex but you can also look into display grid to achieve the same


Protoplasmoid299

Fllllleeeexxxxxxx


Korayzzz

Okay, why didn't you Google that? Or simply take a 30mins of css course from YouTube, they would show that very quickly in every tutorial. Wow


rushadee

Y’all remember the days before flexbox? Where all we had were nested tables and floats. Yeah those days can suck it. Praise be flexbox and grid.


GeorgegoldmanJohn

Use the center tag.


julian88888888

fyi you're shadowbanned


TaylorSwiftStan89

no he's not


julian88888888

Yes, they are, I had to manually approve their comment. https://www.reddit.com/user/GeorgegoldmanJohn will show you the user doesn't exist.


thedivtagguy

Ah. I thought you meant you were shadowbanning them for using the center tag.


csmkt

CSS flex


teacoat___

Step 1: learn to Google your problems. Seriously. This question has been answered millions of times and there is no reason you should post this on reddit rather than spending five seconds figuring it out yourself.


ClassicPart

In general I'd agree, because there's no shortage of questions posted that can be copy-pasted right into Google for the answer on the first page of results. But I'm willing to give this one a pass simply due to the effort put into the question, giving a visual example of what was required instead of just going "X doesn't work". If all support queries were like this, life would be good, and perhaps this can serve as an example of a good query for future visitors. (It won't, people will continue posting shit, but I can hope.)


dna113p

Draw it in the center


Hyper-Cloud

Use Flex or Grid


wasdninja

Just center the div by centering it, duh!


[deleted]

[удалено]


Coopexx

Next time look this up in the internet. There are already many newbies that already asked these questions on sites like stack overflow etc.


-KuroOkami-

Css flexbox or grid would do the trick..but you could also use vertical-align property, it can only be used with inline, and inline-block elements though


uaaR

The easiest would be to apply display of grid and use the place-items: center and you‘re done with 2 lines of css


cgeopapa

I love flex box


blckJk004

Flexbox.


rachitkhurana007

.parent { display: flex; align-items: center; }