NSLayoutConstraints code to center a view and maintain its aspect ratio
If you want to center the red box horizontally, then you want to equate the views' CenterX, not CenterY. So that constraint should look like this:
[NSLayoutConstraint constraintWithItem:contentView
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterX
multiplier:1.f constant:0.f]];
Then on the first constraints, the constraints you have there are ambiguous since there is more than one way to satisfy >=0
margin on each side and <=400
in width. A better way would be to say exactly what you said in your question, which is that you need the width to be <=400 and you would like the margins to be 0 if possible.
So something like this:
[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(0@900)-[contentView(<=400)]-(0@900)-|"
options:0 metrics:0 views:views]];
I believe that gets you want you want?