What's the best way to make a block of text stay within a fixed length and width that is within a div?

So for example if I have a div container 500px all around, and I want to make a block of text within that div that seems to be contained in another box like 250px all around without changing the size of the original div container.

Are you talking about a nested <div> in a situation like this? …

image

div.1 {
  width: 500px;
  margin: auto;
}


/*  same idea applies if the nested  container is a <span> instead of a <div> */

div.2 {
  max-width: 250px;  /* set width of the div (which is inside the bigger div */
  word-wrap: break-word;   /*break long words so they wrap onto next line */
  margin: auto;
}

You probably need to add more stuff to get the inner box and text aligned to your liking.

You could also use a <p> or <span> and do something similar as above.

div.ex1 {
  width: 500px;
  margin: auto;
  border: 3px solid #73AD21;
}

p.ex2 {
  max-width: 250px;
  margin: auto;  
  word-wrap: break-word;
}

image

Both <p> and <div> are block-line elements.
<span> is an inline element.

See:
HTML Block and Inline Elements

Note:

Div, and especially span, should only be used as necessary to provide structure (positioning, layout flow, etc ) and grouping of elements, since they are just containers and have no semantic meaning. In other words, resist the temptation to use a <span> simply to apply styling. There’s often a more appropriate and meaningful element to use for styling.

Ok thanks. Is the only way I can center (both vertically and horizontally) text/img inside of a div is to make another div inside of it?

Not really, but grouping elements is often a good idea (or needed) for various reasons. But you can center elements in many ways.

However, without some specific example of what you are trying to do, we can’t really say all that much.

Exactly.

@gtrman97 I was just trying to get some clarification about what you meant. My reply above was just a few examples based on what I thought you were trying to do.

I can’t post every possible solution because as lasjorg said, there are many.

But I just now came across this blog which explains how to use a flexbox for centering and seems way easier than the way I’ve done it in the past (pre-flexbox).

I’ll admit, my CSS knowledge is outdated/deprecated in many areas. The last website I made was for my own business over 10yrs ago. I am not a WebDev (or any other kind of Dev) nor do I deal with Web Design on a daily basis. I’m just an old I.T. guy learning to code.

How to Center in CSS with Flexbox

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.