-1

I'd like to make an element 400 px wide, if that fits the screen, and otherwise just give it the full width of the screen.

So I don't want the element to overflow beyond the screen.

How do I do this actually?

I've tried setting max-width to 400px, that works partly but it doesn't (of course) set the initial size. If I also put width=100% on it I notice that as I make the window smaller at a certain point the item starts (slightly) overflowing off the screen - it doesn't do that with only max-width set.

1
  • are you wanting to set a max-width of an element to 400px and otherwise set it to 100% width? Can you show us your codes and samples of desire results? Your question is not very clear Nov 15, 2018 at 22:24

2 Answers 2

2

To have a set width and a max width you can do the following:

element {
    width: 100%;
    max-width: 400px;
{

This will set the default width of your element to 100% of the elements parent, but will cap the width at 400px. One thing to take note of is that this will make the elements width 100% of the PARENT to your element. Not of the window.

2

In this example, the flex items are set to evenly occupy the entirety of its parent's width. But, they will only go as far as 400px in a screen that fits 400px. Otherwise, they're as big as their parent will allow them.

#flex-container {
  display: flex;
  background-color: green;
  height: 50vh;
  justify-content: center;
  align-items: center;
}

#flex-item-1 {
  flex: 1 0 0;
  background-color: red;
  height: inherit;
  max-width: 400px;
}

#flex-item-2 {
  flex: 1 0 0;
  background-color: orange;
  height: inherit;
  max-width: 400px;
}
<div id="flex-container">
  <div id="flex-item-1"></div>
  <div id="flex-item-2"></div>
</div>

Also, here's a working example

On the side note, check out this guide for flexbox :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.